How To Break A Dictionary Into A List Of Dictionaries In Python?
I'm trying to convert a dictionary into a list, which contains many dictionaries. for example: input: { 'first-name':'foo', 'last-name':'bar', 'gender':'unknown', '
Solution 1:
Using list comprehension
items()
method is used to return the list with all dictionary keys with values.
Ex.
dict1 = {
'first-name':'foo',
'last-name':'bar',
'gender':'unknown',
'age':99
}
new_list = [{k:v} for k,v in dict1.items() ]
print(new_list)
O/P:
[{'first-name': 'foo'}, {'last-name': 'bar'}, {'gender': 'unknown'}, {'age': 99}]
Another solution suggested by @josoler
new_list = list(map(dict, zip(dict1.items())))
Solution 2:
Dict = {
'first-name':'foo',
'last-name':'bar',
'gender':'unknown',
'age':99
}
list = [(key, value) for key, value inDict.items()]
list >> [('first-name':'foo'), ('last-name':'bar'), ('gender':'unknown'),('age':99)]
This is the simplest way to Convert dictionary to list of tuples
Reference : Python | Convert dictionary to list of tuples
Solution 3:
>>> d={
... 'first-name':'foo',
... 'last-name':'bar',
... 'gender':'unknown',
... 'age':99... }
>>> [{k: v} for (k, v) in d.items()]
[{'first-name': 'foo'}, {'last-name': 'bar'}, {'gender': 'unknown'}, {'age': 99}]
Solution 4:
An alternative method:
>>> [dict([i]) for i in d.items()]
[{'gender': 'unknown'}, {'age': 99}, {'first-name': 'foo'}, {'last-name': 'bar'}]
Solution 5:
k={
'first-name':'foo',
'last-name':'bar',
'gender':'unknown',
'age':99
}
s =list(map(lambda x:{x[0]:x[1]},k.items() ))
output
[{'first-name': 'foo'},
{'last-name': 'bar'},
{'gender': 'unknown'},
{'age': 99}]
Post a Comment for "How To Break A Dictionary Into A List Of Dictionaries In Python?"