Reputation: 1
I am trying to make a master dictionary from preexisting lists and dictionaries. I am having a hard time getting it to work like I think it should. I have a list of student names.
names=[Alice, Bob, Charles, Dan]
I then have 2 dictionaries that have info based on student ID number and another piece of info.
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.
How can I make a master dictionary to give me all of a student's information? Here's what I've tried based on reading answers to other questions.
Dicta=dict(zip(names, dict1))
Dictb=dict(zip(names, dict2))
Dict=dict(zip(Dicta, Dictb))
Here's the sort of answer I'd like to get.
>Dict[Alice]
>>>'100, 9, 9721234567'
#this is Alice's ID, grade level, and home phone
Upvotes: 0
Views: 216
Reputation: 177526
names
is ordered, but the keys of a dict
are unordered, so you can't rely on zip(names,dict1)
to correctly match names with keys (student ID). For example:
>>> d = {'100':1,'101':2,'102':3,'103':4}
>>> d
{'102': 3, '103': 4, '100': 1, '101': 2} # keys not in order declared.
You need one more dict
matching names to student ID. Below I've added an ordered list of IDs then create that dictionary. Then I use a dict comprehension to compute the combined dictionary.
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']
Output:
{'Bob': ('101', 9, 6071234567L), 'Charles': ('102', 11, 9727654321L), 'Alice': ('100', 9, 9721234567L), 'Dan': ('103', 10, 6077654321L)}
('100', 9, 9721234567L)
Upvotes: 2