【问题标题】:how to loop iteratively through 2 dictionaries and create another dictionary?如何遍历 2 个字典并创建另一个字典?
【发布时间】: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


【解决方案1】:

编辑答案:

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

【讨论】:

  • 安德烈,抱歉。我输入了错误的数据集,刚刚更新了它。尽管如此,还是非常感谢您的解决方案。你能帮忙更新数据集吗(字典列表而不是集合)。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多