how to convert list of dict to dict

后端 未结 8 816
执笔经年
执笔经年 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条回答
  •  Happy的楠姐
    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']}`
    

提交回复
热议问题