开发者

Python: Zip dict with keys [duplicate]

开发者 https://www.devze.com 2023-02-14 21:22 出处:网络
This question already has answers here: How can I make a dictionary (dict) from separate lists of keys and values?
This question already has answers here: How can I make a dictionary (dict) from separate lists of keys and values? (21 answers) Closed 9 years ago.

I have:

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

I want:

list_n开发者_JS百科um_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)]


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

gives:

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


If the initial lists are very long, you might want to use itertools.izip() instead of zip() for slightly improved performance and less memory usage, but apart from this I can't think of a significantly "better" way to do it.


Declare a new variable which are the keys 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's definitely more elegant when there are more keys (which is why I started hunting for this solution in the first place :)

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

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

精彩评论

暂无评论...
验证码 换一张
取 消