how to convert list of dict to dict

后端 未结 8 805
执笔经年
执笔经年 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-12 19:19

    Let's not over complicate this:

    simple_dictionary = dict(data[0])
    
    0 讨论(0)
  • 2020-12-12 19:23

    The best approach would be dict((key, val) for k in data for key, val in k.items())

    0 讨论(0)
  • 2020-12-12 19:25

    With python 3.3 and above, you can use ChainMap

    A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.

    from collections import ChainMap
    
    data = dict(ChainMap(*data))
    
    0 讨论(0)
  • 2020-12-12 19:33

    Just in case you wanted a functional alternative (also assuming the names are wanted as the new keys), you could do

    from toolz.curried import *
    
    data = [{'name': 'John Doe', 'age': 37, 'sex': 'M'},
            {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
            {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}]
    
    newdata = pipe(data, 
                   map(lambda x: {x['name']: dissoc(x, 'name')}),
                   lambda x: merge(*x)
    )
    
    print(newdata)
    
    0 讨论(0)
提交回复
热议问题