Reputation: 19
I am looking to create a new dictionary from a list of dictionaries, with a specific property from those dictionaries as a new key.
Here is an example to better outline the concept:
Original
[
{
"id":"asdf1234",
"firstname":"john",
"lastname":"smith",
"age":30
},
{
"id":"sdfg2345",
"firstname":"jane",
"lastname":"doe",
"age":25
},
{
"id":"dfgh3456",
"firstname":"billy",
"lastname":"ericson",
"age":35
}
]
Transformed
{
"asdf1234":{
"firstname":"john",
"lastname":"smith",
"age":30
},
"sdfg2345":{
"firstname":"jane",
"lastname":"doe",
"age":25
},
"dfgh3456":{
"firstname":"billy",
"lastname":"ericson",
"age":35
}
}
I understand this can be done using this ugly code, I'm looking for a more concise and elegant way to do so.
transformed = {}
for i in range(len(data)):
transformed[data[i]['id']] = data[i]
del transformed[data[i]['id']]['id']
return transformed
Upvotes: 2
Views: 353
Reputation: 10009
dicts = [
{
"id":"asdf1234",
"firstname":"john",
"lastname":"smith",
"age":30
},
{
"id":"sdfg2345",
"firstname":"jane",
"lastname":"doe",
"age":25
},
{
"id":"dfgh3456",
"firstname":"billy",
"lastname":"ericson",
"age":35
}
]
new_dicts = {d.pop('id'): d for d in dicts}
Upvotes: 1
Reputation: 1836
This can be done using Dictionary Comprehension, and the pop()
method. Here's an example:
return {item.pop('id'):item for item in data}
You would replace id
with whatever property you would like to set as the key.
Upvotes: 5