Alex Rivera | Logout

How do I convert a list of dicts to a dict?

Asked 2011-03-08T17:51:00.933
88

How can I convert a list of dicts to a dict? Below is the list of dicts:

data = [{'name': 'John Doe', 'age': 37, 'sex': 'M'},
        {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
        {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}]

I want to convert this to:

data = {'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'}}
Edit
Report

2 Answers

117

A possible solution using names as the new keys:

new_dict = {}
for item in data:
   name = item['name']
   new_dict[name] = item

With Python 3.x you can also use dict comprehensions for the same approach in a more nice way:

new_dict = {item['name']:item for item in data}

As suggested in a comment by Paul McGuire, if you don't want the name in the inner dict, you can do:

new_dict = {}
for item in data:
   name = item.pop('name')
   new_dict[name] = item
answered 2011-03-08T17:58:36.113
2

Perhaps you want the name to be the key? You don't really specify, since your second example is invalid and not really meaningful.

Note that my example removes the key "name" from the value, which may be desirable (or perhaps not).

data = [{'name': 'John Doe', 'age': 37, 'sex': 'M'},
        {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
        {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}]
newdata = {}
for entry in data:
    name = entry.pop('name') #remove and return the name field to use as a key
    newdata[name] = entry
print newdata
##{'Bill Clinton': {'age': 57, 'sex': 'M'},
## 'John Doe': {'age': 37, 'sex': 'M'},
## 'Lisa Simpson': {'age': 17, 'sex': 'F'}}
print newdata['John Doe']['age']
## 37
answered 2011-03-08T18:05:20.837

Your Answer