how to convert list of dict to dict

后端 未结 8 829
执笔经年
执笔经年 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:17

    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
    

提交回复
热议问题