简体   繁体   English

如何将字典列表转换为字典

[英]how to convert list of dict to dict

How to convert list of dict to dict.如何将字典列表转换为字典。 Below is the list of dict以下是字典列表

data = [{'name': 'John Doe', 'age': 37, 'sex': 'M'},
        {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
        {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}]

to

data = {'John Doe': {'name': 'John Doe', 'age': 37, 'sex': 'M'},
        'Lisa Simpson': {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
        'Bill Clinton': {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}}

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:使用 python 3.x,您还可以以更好的方式将 dict 推导用于相同的方法:

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:正如 Paul McGuire 在评论中所建议的,如果您不想在内部 dict 中使用该名称,您可以执行以下操作:

new_dict = {}
for item in data:
   name = item.pop('name')
   new_dict[name] = item

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']}`

With python 3.3 and above, you can use ChainMap使用python 3.3及以上,你可以使用ChainMap

A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. ChainMap 将多个字典或其他映射组合在一起以创建单个可更新视图。 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))

试试这个方法:

dict((key, val) for k in data for key, val in k.items())

让我们不要把它复杂化:

simple_dictionary = dict(data[0])

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

My 5 cents, didn't like any of answers:我的 5 美分,不喜欢任何答案:

from functools import reduce
collection = [{'hello': 1}, {'world': 2}]
answer = reduce(lambda aggr, new: aggr.update(new) or aggr, collection, {})
indice = 1
mlista = [{'uno':1,'dos':2,'tres':3}, {'cuatro':4,'cinco':5,'seis':6}]
mndic = {}
mndic = dict((mlista.index(d)+indice, d) for d in mlista)
print(mndic)
#output {1: {'uno': 1, 'dos': 2, 'tres': 3}, 2: {'cuatro': 4, 'cinco': 5, 'seis': 6}}

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)
import pandas as pd
data = [{'name': 'John Doe', 'age': 37, 'sex': 'M'},
        {'name': 'Lisa Simpson', 'age': 17, 'sex': 'F'},
        {'name': 'Bill Clinton', 'age': 57, 'sex': 'M'}]

print(pd.DataFrame(data).to_dict())

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'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM