Zuz
Zuz

Reputation: 57

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.

Upvotes: 0

Views: 123

Answers (2)

Yakir Tsuberi
Yakir Tsuberi

Reputation: 247

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]

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121634

You can use a list comprehension over the dict.items() pairs:

[{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).

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

Upvotes: 6

Related Questions