how to convert list of dict to dict

后端 未结 8 804
执笔经年
执笔经年 2020-12-12 19:00

How to convert list of dict to dict. Below is the list of dict

data = [{\'name\': \'John Doe\', \'age\': 37, \'sex\': \'M\'},
        {\'name\': \'Lisa Simp         


        
8条回答
  •  自闭症患者
    2020-12-12 19:15

    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
    

提交回复
热议问题