2017-08-10 110 views
0

我想从已有的列表和字典中制作一个主字典。我很难让它像我认为的那样工作。 我有一个学生姓名列表。从列表和其他字典中嵌套字典

names=[Alice, Bob, Charles, Dan]

我再有2个字典根据学生的身份证号和另一块信息的有信息。

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,年级和家庭电话

回答

2

names是有序的,但dict的关键是无序的,所以你不能依靠zip(names,dict1)正确匹配的钥匙名(学生卡)。例如:

>>> 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列表,然后创建该字典。然后,我使用词典理解来计算组合字典。

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)