Merging three lists into into one dictionary

dictionary, list, merge, python

Solution

You were on the right track with `zip`, but beware that:

The returned list is truncated in length to the length of the shortest argument sequence.

If you're fine with that, you can zip your data into a list of tuples, zip the keys, and hand everything off to `dict()`.

If you'd like to handle missing values, checkout `itertools` `izip_longest` (Python 2) or `zip_longest` (Python 3) where

If the iterables are of uneven length, missing values are filled-in with fillvalue.

try:
    # Python 2
    from itertools import izip_longest
    zip_longest = izip_longest
except ImportError:
    # Python 3
    from itertools import zip_longest

from pprint import pprint


def main():
    maker =['Horsey', 'Ford', 'Overland', 'Scripps-Booth', 'FutureX', 'FutureY']
    year = ['1899', '1909', '1911', '1913', '20xx']
    model = ['Horseless', 'Model T', 'OctoAuto', 'Bi-Autogo']

    car_data = dict(zip(maker, zip(year, model)))
    car_data_longest = {mk: (yr, md) for mk, yr, md in zip_longest(maker, year, model)}

    pprint(car_data)
    pprint(car_data_longest)

Output:

{'Ford': ('1909', 'Model T'),
 'Horsey': ('1899', 'Horseless'),
 'Overland': ('1911', 'OctoAuto'),
 'Scripps-Booth': ('1913', 'Bi-Autogo')}
{'Ford': ('1909', 'Model T'),
 'FutureX': ('20xx', None),
 'FutureY': (None, None),
 'Horsey': ('1899', 'Horseless'),
 'Overland': ('1911', 'OctoAuto'),
 'Scripps-Booth': ('1913', 'Bi-Autogo')}

Problem

I need to merge three lists into one dictionary. These lists are from reading a txt file I formatted, and here is a snippet from that file: ``` maker =['Horsey', 'Ford', 'Overland', 'Scripps-Booth'] year = ['1899', '1909', '1911', '1913'] model = ['Horseless', 'Model T', 'OctoAuto', 'Bi-Autogo'] ``` Into the following: ``` car_dict = {'Horsey':1899,'Horseless','Ford':1909,'Model T','Overland' : 1911, 'OctoAuto', 'Scripps-Booth' : 1913, 'Bi-Autogo'} ``` Here is what I did: ``` def car_data_merge(car_maker,car_model,car_year): car_dict = {} car_merge = [] car_dict = defaultdict(partial(defaultdict,list)) for (car_maker,car_model,car_year) in zip(car_maker,car_model,car_year): car_dict[car_year][car_model].append(car_maker) print(car_dict) ``` When I enter this I get: ``` {'Horsey': defaultdict(<class 'list'>, {'1899': ['Horseless']}) ``` Not all the data from list is shown and I don't want the `defaultdict` shown. When I tried the following: ``` def car_data_merge(car_maker,car_data): car_dict = {} car_merge = [] car_merge = zip(car_maker,car_data) car_dict = dict(car_merge) print(car_dict) ### car_data holds both year and model #### ``` Only part of the data shows up: ``` 'Horsey':'Horseless',':1909,'Model T ``` What should I do?

Original source