triplejjj
triplejjj

Reputation: 19

Concise way to create new dictionary with specific property as key, from list of dictionaries in Python

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

Answers (2)

ShikharDua
ShikharDua

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

Jack Casey
Jack Casey

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

Related Questions