Merge Three List To Dictionary But Everything Is Out Of Place/not Printed
I asked this question yesterday Merging three lists into into one dictionary The number one answer was the most correct in what I needed but re-looking at MY automobile.txt file I
Solution 1:
Recommendation
You could do a dictionary of lists of tuples. Defaultdict is your friend.
Code
from collections import defaultdict
year= [1958, 1909, 1958, 1958, 1961, 1961]
maker = ['Ford', 'Ford', 'Lotus', 'MGA', 'Amphicar', 'Corvair']
model = ['Edsel', 'Model T', 'Elite', 'Twin Cam', '', '']
d = defaultdict(list)
for maker, model, yearin zip(maker, model, year):
d[maker].append((model, year))
Result
>>>from collections import defaultdict>>>>>>year = [1958, 1909, 1958, 1958, 1961, 1961]>>>maker = ['Ford','Ford','Lotus','MGA', 'Amphicar', 'Corvair']>>>model = ['Edsel', 'Model T', 'Elite', 'Twin Cam', "", ""]>>>>>>d = defaultdict(list)>>>for maker, model, year inzip(maker, model, year):... d[maker].append((model, year))...>>>from pprint import pprint>>>pprint(dict(d))
{'Amphicar': [('', 1961)],
'Corvair': [('', 1961)],
'Ford': [('Edsel', 1958), ('Model T', 1909)],
'Lotus': [('Elite', 1958)],
'MGA': [('Twin Cam', 1958)]}
You can also use your izip_longest
:
from itertools import izip_longest
...
d = defaultdict(list)
for maker, model, yearin izip_longest(maker, model, year):
d[maker].append((model, year))
Then you get None for the other values.
Post a Comment for "Merge Three List To Dictionary But Everything Is Out Of Place/not Printed"