简体   繁体   English

将字典转换为字典python列表

[英]Convert a dict into a list of dicts python

I would like to convert the following dictionary: 我想转换以下字典:

{'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']}

into: 变成:

[{'Stockholm':['235', '35']},{'Helsinki': ['285', '15']},
{'Copenhagen':   ['180', '60']},...,{'Athens': ['285', '205']}] 

I'm out of ideas how to convert it. 我不知道如何转换它。

You can use a list comprehension over the dict.items() pairs: 您可以对dict.items()对使用列表理解:

[{k: v} for k, v in d.items()]  # where d is your dictionary

This creates a separate dictionary for each key-value pair. 这将为每个键值对创建一个单独的字典。

You can't rely on any order in the input dictionary, so the output order will depend on the insertion and deletion history of the dictionary (unless you are using Python 3.6 or up). 您不能依赖输入字典中的任何顺序,因此输出顺序将取决于字典的插入和删除历史记录(除非您使用的是Python 3.6或更高版本)。

Demo: 演示:

>>> 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']}]

The simple way: 简单的方法:

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']}
d = [d]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM