[英]dictionary containing a list of dictionaries
Newbie here, so apologies for a duplicate/silly question but I can't find the answer. 这里有新手,所以对复制/愚蠢的问题道歉,但我找不到答案。
I am trying to store the contents of a list (of dictionaries) into a new dictionary. 我试图将列表(字典)的内容存储到新字典中。
a={}
b=[]
c={"Name":"Claude","Surname":"Verde","Age":"35","City":"Paris"}
b.append(c)
c={"Name":"Jean","Surname":"Claude","Age":"22","City":"Paris"}
b.append(c)
c={"Name":"Sam","Surname":"Smith","Age":"42","City":"London"}
b.append(c)
c={"Name":"James","Surname":"Jones","Age":"44","City":"London"}
b.append(c)
for i in range(len(b)):
if b[i]['City'] == 'Paris':
a["Paris"]=([b[i]])
elif b[i]['City'] == 'London':
a["London"]=([b[i]])
a
Result: 结果:
{'Paris': [{'Name': 'Jean',
'Surname': 'Claude',
'Age': '22',
'City': 'Paris'}],
'London': [{'Name': 'James',
'Surname': 'Jones',
'Age': '44',
'City': 'London'}]}
However, I want a dictionary containing all residents of a city. 但是,我想要一本包含所有城市居民的字典。
The code above only stores the second, not the first, resident in the list. 上面的代码只存储列表中的第二个,而不是第一个。
ie hoping for the below output. 即希望以下输出。
How can I achieve this? 我怎样才能做到这一点?
Any help greatly appreciated. 任何帮助非常感谢。 Thanks
谢谢
{'Paris': [{'Name': 'Claude',
'Surname': 'Verde',
'Age': '35',
'City': 'Paris'},{'Name': 'Jean',
'Surname': 'Claude',
'Age': '22',
'City': 'Paris'}],
'London': [{'Name': 'Sam',
'Surname': 'Smith,
'Age': '42',
'City': 'London'},{'Name': 'James',
'Surname': 'Jones',
'Age': '44',
'City': 'London'}]}
When you initialize a, I would approach it like this: 当你初始化a时,我会像这样接近它:
a = {}
b=[]
c={"Name":"Claude","Surname":"Verde","Age":"35","City":"Paris"}
b.append(c)
c={"Name":"Jean","Surname":"Claude","Age":"22","City":"Paris"}
b.append(c)
c={"Name":"Sam","Surname":"Smith","Age":"42","City":"London"}
b.append(c)
c={"Name":"James","Surname":"Jones","Age":"44","City":"London"}
b.append(c)
for i in range(len(b)):
if b[i]['City'] not in a.keys():
a[b[i]['City']] = []
for i in range(len(b)):
a[b[i]['City']].append(b[i]])
As a note: I'm pretty sure you can combine those for loops like this: 作为一个注释:我很确定你可以像这样组合循环:
for i in range(len(b)):
if b[i]['City'] not in a.keys():
a[b[i]['City']] = []
a[b[i]['City']].append(b[i]])
Use itertools.groupby
使用
itertools.groupby
>>> lst = [
... {"Name":"Claude","Surname":"Verde","Age":"35","City":"Paris"},
... {"Name":"Jean","Surname":"Claude","Age":"22","City":"Paris"},
... {"Name":"Sam","Surname":"Smith","Age":"42","City":"London"},
... {"Name":"James","Surname":"Jones","Age":"44","City":"London"}]
>>>
>>> from itertools import groupby
>>> f = lambda d: d['City']
>>> res = {k:list(v) for k,v in groupby(sorted(lst, key=f), f)}
>>> pprint(res)
{'London': [{'Age': '42', 'City': 'London', 'Name': 'Sam', 'Surname': 'Smith'},
{'Age': '44', 'City': 'London', 'Name': 'James', 'Surname': 'Jones'}],
'Paris': [{'Age': '35', 'City': 'Paris', 'Name': 'Claude', 'Surname': 'Verde'},
{'Age': '22', 'City': 'Paris', 'Name': 'Jean', 'Surname': 'Claude'}]}
Use itertools.groupby
: 使用
itertools.groupby
:
from itertools import groupby
b = [{'Name': 'Claude', 'Surname': 'Verde', 'Age': '35', 'City': 'Paris'},
{'Name': 'Jean', 'Surname': 'Claude', 'Age': '22', 'City': 'Paris'},
{'Name': 'Sam', 'Surname': 'Smith', 'Age': '42', 'City': 'London'},
{'Name': 'James', 'Surname': 'Jones', 'Age': '44', 'City': 'London'}]
print({k: list(g) for k, g in groupby(b, key=lambda x: x['City'])})
# {'Paris': [{'Name': 'Claude', 'Surname': 'Verde', 'Age': '35', 'City': 'Paris'}, {'Name': 'Jean', 'Surname': 'Claude', 'Age': '22', 'City': 'Paris'}],
# 'London': [{'Name': 'Sam', 'Surname': 'Smith', 'Age': '42', 'City': 'London'}, {'Name': 'James', 'Surname': 'Jones', 'Age': '44', 'City': 'London'}]}
You can use the get
method that has a default argument: 您可以使用具有默认参数的
get
方法:
a["Paris"]= a.get("Paris", []) + [b[i]]
The drawback is that it will create a new list every time you insert an element. 缺点是每次插入元素时都会创建一个新列表。 However, it's fine if you don't have much data.
但是,如果您没有太多数据,那就没问题。
This gives, with a few improvements: 这给了一些改进:
for person in b:
if person['City'] in ('Paris', 'London'):
a[person['City']] = a.get(person['City'], []) + [person]
If you don't want to recreate a new list: 如果您不想重新创建新列表:
for person in b:
if person['City'] in ('Paris', 'London'):
new_city = a.get(person['City'], [])
new_city.append(person)
a[person['City']] = new_city
Or you could also use a defaultdict
instead of a dict
. 或者您也可以使用
defaultdict
而不是dict
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.