Search code examples
pythonlistdictionaryzipkey

How to populate a python dictionary when keys are strings and values are lists?


I need to create a dictionary as shown below:

d = {'a': [2, 3, 4], 'b': [3, 4, 6], 'c': [2, 5, 9]}

I have keys in the form of a list

keys = ['a', 'b', 'c'] 

and values are present as separate lists

values = [[2, 3, 2], [3, 4, 5], [4, 6, 9]]. 

I've tried using

d(zip(keys, values))

but it returns a dictionary as

{'a': [2, 3, 2], 'b': [3, 4, 5], 'c': [4, 6, 9]}

Is there any other method or correction?


Solution

  • You should zip your values list before combining it with your keys:

    >>> keys = ['a', 'b', 'c']
    >>> values = [[2, 3, 2], [3, 4, 5], [4, 6, 9]]
    >>> dict(zip(keys, zip(*values)))
    {'a': (2, 3, 4), 'b': (3, 4, 6), 'c': (2, 5, 9)}
    

    If the values must be lists (and not tuples), you can do the following:

    >>> dict(zip(keys, map(list, zip(*values))))
    {'a': [2, 3, 4], 'b': [3, 4, 6], 'c': [2, 5, 9]}