了解Python的zip功能。我可以这样做
list_keys = ['fname','lname','dob']
list_data = ['bob','smith','12121950']
keys_and_data = dict(zip(list_keys,list_data))
print keys_and_data
#output
{'lname': 'smith', 'dob': '12121950', 'fname': 'bob'}
现在我想弄清楚如何让它发挥作用
list_keys = ['fname','lname','dob']
list_data = [['bob','smith','12121950'],['john','jones','10101940']]
keys_and_data = ??
print keys_and_data
#output
{['lname': 'smith', 'dob': '12121950', 'fname': 'bob'],
['lname': 'jones', 'dob': '10101940', 'fname': 'john']}
如何让python重复键?
答案 0 :(得分:4)
在列表解析中循环list_data
:
keys_and_data = [dict(zip(list_keys, data)) for data in list_data]
演示:
>>> list_keys = ['fname','lname','dob']
>>> list_data = [['bob','smith','12121950'],['john','jones','10101940']]
>>> [dict(zip(list_keys, data)) for data in list_data]
[{'lname': 'smith', 'dob': '12121950', 'fname': 'bob'}, {'lname': 'jones', 'dob': '10101940', 'fname': 'john'}]