Answer provided by Python King (simple as this print({obj['name']:obj for obj in data})
)
data = [{'name': 'John Doe', 'age': 37, 'sex': 'M'},
{'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
{'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}]
# answer
print({obj['name']:obj for obj in data})
result:
{
'John Doe': {'name': 'John Doe', 'age': 37, 'sex': 'M'},
'Lisa Simpson': {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
'Bill Clinton': {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}
}
Nice ex also in one answers but how it done python way simple
listofdicts = [
{1:2,3:4},
{5:6,7:9},
{10:8,13:22}
]
old = {}
for x in listofdicts:
old = {**old, **x}
# not dict not repeat properties
print(old)
result: {1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}
# important not dict not allow repeat property so if repeated property the prop and val will be last one found
more ideas
y = {}
for x in [{dict1['prop']:dict1['val']} for dict1 in [{'prop': 'a', 'val': '1'},{'prop': 'b', 'val': '2'}]]:
y = {**y, **x}
print(y)
example 2
test = {'old': 1}
test = {**old, **{'new': 2}}
result: {'a': '1', 'b': '2'}
complex example one property only dicts
print({list(testit.items())[0][0]:list(testit.items())[0][1] for testit in [{dict1['prop']:dict1['val']} for dict1 in [{'prop': 'a', 'val': '1'},{'prop': 'b', 'val': '2'}]]})
result: {'a': '1', 'b': '2'}
more clear done above
print({ obj['info']:obj['info2'] for obj in [{'info': 'title1', 'info2': 'date1'}, {'info': 'title2', 'info2': 'date2'}]})
{'Lisa Simpson': {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'} ...}
) – Drachma