列表和其他词典中的嵌套词典

时间:2017-08-10 17:14:52

标签: python-2.7 list dictionary nested

我正在尝试从预先存在的列表和词典中创建一个主词典。我很难让它像我认为的那样工作。 我有一个学生姓名列表。

names=[Alice, Bob, Charles, Dan]

然后我有2个字典,其中包含基于学生ID号和另一条信息的信息。

dict1={'100':9, '101:9, '102':11, '103':10} #the keys are student ID and the values are the grade level of the student. Alice is 100, Bob=101...

dict2={'100':9721234567, '101':6071234567, '103': 9727654321, '104':6077654321} #this dictionary gives the home phone number as a value using the student ID as a key.

如何制作一本主词典,以便向我提供学生的所有信息?这是我在阅读其他问题的答案时尝试过的。

Dicta=dict(zip(names, dict1))
Dictb=dict(zip(names, dict2))
Dict=dict(zip(Dicta, Dictb))

以下是我想得到的答案。

>Dict[Alice]
>>>'100, 9, 9721234567'

#这是Alice的ID,年级和家庭电话

1 个答案:

答案 0 :(得分:2)

names已订购,但dict的密钥无序,因此您无法依靠zip(names,dict1)将名称与密钥(学生ID)正确匹配。例如:

>>> d = {'100':1,'101':2,'102':3,'103':4}
>>> d
{'102': 3, '103': 4, '100': 1, '101': 2} # keys not in order declared.

您还需要一个dict个匹配的学生ID名称。下面我添加了一个有序的ID列表,然后创建该字典。然后我用dict理解来计算组合字典。

names = ['Alice','Bob','Charles','Dan']
ids = ['100','101','102','103']

dictn = dict(zip(names,ids))
dict1={'100':9, '101':9, '102':11, '103':10}
dict2={'100':9721234567, '101':6071234567, '102': 9727654321, '103':6077654321}

Dict = {k:(v,dict1[v],dict2[v]) for k,v in dictn.items()}
print Dict
print Dict['Alice']

输出:

{'Bob': ('101', 9, 6071234567L), 'Charles': ('102', 11, 9727654321L), 'Alice': ('100', 9, 9721234567L), 'Dan': ('103', 10, 6077654321L)}
('100', 9, 9721234567L)
相关问题