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))
精彩评论