包含字典列表的字典

时间:2018-08-03 17:28:51

标签: python 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

结果:

{'Paris': [{'Name': 'Jean',
   'Surname': 'Claude',
   'Age': '22',
   'City': 'Paris'}],
 'London': [{'Name': 'James',
   'Surname': 'Jones',
   'Age': '44',
   'City': 'London'}]}

但是,我想要一本包含城市所有居民的字典。

上面的代码仅存储列表中的第二个居民,而不是第一个居民。

即希望获得以下输出。

我该如何实现?

任何帮助,我们将不胜感激。谢谢

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

4 个答案:

答案 0 :(得分:2)

初始化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]])

请注意: 我很确定您可以将这些for循环组合在一起:

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]])

答案 1 :(得分:0)

使用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'}]}

答案 2 :(得分:0)

使用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'}]}

答案 3 :(得分:0)

您可以使用具有默认参数的get方法:

a["Paris"]= a.get("Paris", []) + [b[i]]

缺点是每次插入元素时都会创建一个新列表。但是,如果您没有太多数据,那很好。

这会带来一些改进:

for person in b:
    if person['City'] in ('Paris', 'London'):
        a[person['City']] = a.get(person['City'], []) + [person]

如果您不想重新创建新列表:

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

或者您也可以使用defaultdict代替dict