Home > Software design >  convert values of list of dictionaries with different keys to new list of dicts
convert values of list of dictionaries with different keys to new list of dicts

Time:08-28

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

res = list(map(lambda data: {data['name']: data['age']}, d))
print(res) 
  • Related