Reputation: 488
a = [{ 'id': '123', 'name': 'A', 'type': 'software' },
{ 'id': '102', 'name': 'Adfds', 'type': 'software' },
{ 'id': '222', 'name': 'sxds', 'type': 'software' }]
Code is below
{{key:val} for each in a for key,val in each.items()}
Expected out
{ '123': { 'name': 'A', 'type': 'software' },
'102': { 'name': 'Adfds', 'type': 'software' },
'222': { 'name': 'sxds', 'type': 'software' } }
Upvotes: 0
Views: 314
Reputation: 2947
You can use map and lambda to achieve your goal. Just do:
result = dict(map(lambda entry: [entry.pop('id'), entry], a))
print(result)
And it gives:
{'123': {'name': 'A', 'type': 'software'}, '102': {'name': 'Adfds', 'type': 'software'}, '222': {'name': 'sxds', 'type': 'software'}}
Upvotes: 1
Reputation: 982
You can do this:
{e['id']: dict(i for i in e.items() if i[0] != 'id') for e in a}
Upvotes: 1
Reputation: 24049
you can try this:
a=[{ 'id': '123', 'name': 'A', 'type': 'software' }, { 'id': '102', 'name': 'Adfds', 'type': 'software' }, { 'id': '222', 'name': 'sxds', 'type': 'software' }]
b = {}
for item in a:
b[item.pop("id")] = item
b
output:
Upvotes: 1
Reputation: 2399
A dictionary cannot have duplicated keys.
In your example you are adding different values to same key. Here what you had to do:
res = {each["id"]: {"name": each["name"], "type": each["type"]} for each in a}
Upvotes: 1