how to convert list of dict to dict

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

    If the dicts wouldnt share key, then you could use:

    dict((key,d[key]) for d in data for key in d)
    

    Probably its better in your case to generate a dict with lists as values?

    newdict={}
    for k,v in [(key,d[key]) for d in data for key in d]:
      if k not in newdict: newdict[k]=[v]
      else: newdict[k].append(v)
    

    This yields:

    >>> newdict
    `{'age': [37, 17, 57], 'name': ['John Doe', 'Lisa Simpson', 'Bill Clinton'], 'sex': ['M', 'F', 'M']}`
    
    0 讨论(0)
  • 2020-12-12 19:36

    It can be also written as follows,

    data = {0: {'name': 'John Doe', 'age': 37, 'sex': 'M'},
            1: {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
            2: {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}}
    
    0 讨论(0)
提交回复
热议问题