假设你有如下两个list:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
如何转变成:
a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
解决方法:
>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print(dictionary)
{'a': 1, 'b': 2, 'c': 3}
进阶,如果value是一个多级list呢:
keys= ['id', 'name', 'pwd']
values = [[2, '123', '567'],[3, '456', '899']]
解决方法:
>>> keys= ['id', 'name', 'pwd']
>>> values = [[2, '123', '567'],[3, '456', '899']]
# 先遍历rows里面的值,然后在用zip反转
>>> a = [dict(zip(keys,values)) for row in values] if values else None
>>> print(a)
[{'name': [3, '456', '899'], 'id': [2, '123', '567']}, {'name': [3, '456', '899'], 'id': [2, '123', '567']}]