我想转换以下词典:
{'Stockholm': ['235', '35'], 'Helsinki': ['285', '15'],
'Copenhagen': ['180', '60'], 'Berlin': ['185', '85'],
'Prague': ['190', '115'], 'Warsaw': ['260', '105'],
'Moscow': ['370', '80'], 'Sofia': ['275', '170'],
'Ankara': ['340', '190'], 'Athens': ['285', '205']}
成:
[{'Stockholm':['235', '35']},{'Helsinki': ['285', '15']},
{'Copenhagen': ['180', '60']},...,{'Athens': ['285', '205']}]
我没有想法如何转换它。
答案 0 :(得分:6)
您可以对dict.items()
对使用列表理解:
[{k: v} for k, v in d.items()] # where d is your dictionary
这会为每个键值对创建一个单独的字典。
您不能依赖输入字典中的任何顺序,因此输出顺序将取决于字典的插入和删除历史记录(除非您使用的是Python 3.6或更高版本)。
演示:
>>> d = {'Stockholm': ['235', '35'], 'Helsinki': ['285', '15'],
... 'Copenhagen': ['180', '60'], 'Berlin': ['185', '85'],
... 'Prague': ['190', '115'], 'Warsaw': ['260', '105'],
... 'Moscow': ['370', '80'], 'Sofia': ['275', '170'],
... 'Ankara': ['340', '190'], 'Athens': ['285', '205']}
>>> [{k: v} for k, v in d.items()]
[{'Stockholm': ['235', '35']}, {'Helsinki': ['285', '15']}, {'Copenhagen': ['180', '60']}, {'Berlin': ['185', '85']}, {'Prague': ['190', '115']}, {'Warsaw': ['260', '105']}, {'Moscow': ['370', '80']}, {'Sofia': ['275', '170']}, {'Ankara': ['340', '190']}, {'Athens': ['285', '205']}]