【发布时间】:2019-12-01 19:51:51
【问题描述】:
我有一个包含 500000 条记录的列表,每条记录都存储为字典。本质上是一个字典列表。每条记录都有一个“代码”和“计数”。可能有多个具有相同“代码”的记录。
我有一本包含超过 100000 条记录的字典,其中“代码”作为键,而“压缩”作为值。这里的“code”是唯一的,多个“code”可以有相同的“zip”
我想找出每个'zip'对应的'count'并将它们存储在另一个字典中,'zip'作为键,'count'作为值。
我正在编写一个嵌套的 for 循环,但耗时太长。
zip_count = {}
for key1, val1 in dict1.items(): # dictionary with code,zip
for key2, val2 in list1: # this is the list of dictionaries
if key2 == key1: # looking for a match of the code
if val1 in zip_count:
zip_count[val1] = zip_count[val1] + val2
else:
zip_count[val1] = val2
考虑到数据集的大小,这是一个繁琐的过程。
有人可以帮忙吗?这是输入和相同的输出:
List1 =
[{'code': 'A101','count':2},
{'code': 'A102','count':4},
{'code': 'A103','count':5},
{'code': 'A103','count':10},
{'code': 'A104','count':20},
{'code': 'A104','count':0},
{'code': 'A105','count':1},
{'code': 'B101','count':20},
{'code': 'B101','count':30}]
Dict1 =
{'A101': '10001',
'A102': '10001',
'A103': '10002',
'A104': '10004',
'A105': '10005',
'B101': '10010'}
Output --
zip_count (zip and count) = [
'10001' = 7(3+4)
'10002' = 15(5+10)
'10004' = 20 (20+0) etc.
【问题讨论】:
-
您可以编辑您的问题并添加一些示例(小)输入和预期输出吗?
-
将“collections.Counter”与“dict1.values()”一起使用
-
您的输入输出无效。请edit 修复它。这似乎是一件我们可以掩盖的小事,但您需要确保它是正确的。详情请见minimal reproducible example。
标签: python dictionary