结合使用zip( )和dict( )可以很方便的反转字典(交换键值对的位置),示例如下:
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> d
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> d.keys()
['a', 'c', 'b', 'd']
>>> d.values()
[1, 3, 2, 4]
>>> zip(d.values(),d.keys())
[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
>>> dict(zip(d.values(),d.keys()))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
遍历 list,结合zip,dict:
column_names= ('id', 'name', 'pwd') # key
rows = [(2, '123', '567')] # vlaue
# 先遍历rows里面的值,然后在用zip反转
[dict(zip(column_names,row)) for row in rows] if rows else None
>>>
[{'name': '123', 'id': 2, 'pwd': '567'}]
```