Python: Zip dict with keys

I have:

list_nums = [1,18]
list_chars = ['a','d']

I want to:

list_num_chars = [{'num':1, 'char':'a'},
                  {'num':18, 'char':'d'}]

Is there a more elegant solution than:

list_num_chars = [{'num':a, 'char':b} for a,b in zip(list_nums, list_chars)]
+5
source share
3 answers

If the start lists are very long, you can use itertools.izip()instead zip()for a slightly improved performance and less memory usage, but apart from that I cannot think of a much more “better” way to do this.

+2
source
map(dict, map(lambda t:zip(('num','char'),t), zip(list_nums,list_chars)))

gives:

[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]
+3
source

Declare a new variable that is the key to your dict

from itertools import izip
nums  = [1,18]
chars = ['a','d']
keys  = ["num", "char"]      # include list of keys as an input

which gives a slightly more elegant solution, I think.

[dict(zip(keys,row)) for row in izip(nums,chars)]

It is definitely more elegant when there are more keys (which is why I started looking for this solution in the first place :)

If you want, this setting gives the same thing as a generator:

(dict(zip(keys,row)) for row in izip(nums,chars))
+1
source

All Articles