如何迭代遍历2个字典并创建另一个字典?

时间:2019-12-01 19:51:51

标签: python dictionary

我有一个包含500000条记录的列表,每条记录都存储为字典。本质上是字典列表。每个记录都有一个“代码”和“计数”。可能有多个具有相同“代码”的记录。

我有一本字典,其中有超过100000条记录,其中以“代码”为键,但以“ zip”为值。这里的“代码”是唯一的,多个“代码”可能具有相同的“ 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. 

1 个答案:

答案 0 :(得分:0)

编辑答案:

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

d = {}
for item in List1:
    d.setdefault(item['code'], 0)
    d[item['code']] += item['count']

# d now holds {'A101': 2, 'A102': 4, 'A103': 15, 'A104': 20, 'A105': 1, 'B101': 50}

rv = {}
for k, v in d.items():
    rv.setdefault(Dict1[k], 0)
    rv[Dict1[k]] += v

print(rv)

打印:

{'10001': 6, '10002': 15, '10004': 20, '10005': 1, '10010': 50}

注意:dict.setdefault()方法的解释为here

相关问题