convert values of list of dictionaries with different keys to new list of dicts

Question:

I have this list of dicts:

[{'name': 'aly', 'age': '104'}, 
 {'name': 'Not A name', 'age': '99'}]

I want the name value to be the key and the age value to be the value of new dict.

Expected output:

['aly' : '104', 'Not A name': '99']
Asked By: Alo

||

Answers:

This will help you:

d = [
 {'name': 'aly', 'age': '104'}, 
 {'name': 'Not A name', 'age': '99'}
]
dict([i.values() for i in d])
# Result
{'aly': '104', 'Not A name': '99'}

# In case if you want a list of dictionary, use this
[dict([i.values() for i in d])]
# Result
[{'aly': '104', 'Not A name': '99'}]

Just a side note:
Your expected answer looks like a list (because of [ ]) but values inside the list are dictionary (key:value) which is invalid.

Answered By: Shubham Jha

You can initialize the new dict, iterate through the list and add to the new dict:

lst = [{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]

newdict = {}
for item in lst:
  newdict[item['name']] = item['age']
Answered By: codetulpa

If you want output to be single dict, you can use dict comprehension:

output = {p["name"]: p["age"] for p in persons}
>>> {'aly': '104', 'Not A name': '99'}

If you want output to be list of dicts, you can use list comprehension:

output = [{p["name"]: p["age"]} for p in persons]
>>> [{'aly': '104'}, {'Not A name': '99'}]
Answered By: Max Smirnov

Here is the easiest way to convert the new list of dicts

res = list(map(lambda data: {data['name']: data['age']}, d))
print(res) 
Answered By: Omar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.