5

我想创建一个包含公共键和它们的值总和的 finalDic

myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}, ...]

首先找到常用键

commonkey = [{2:1, 3:1}, {2:3, 3:4}, {2:5, 3:6}]

然后求和并按它们的值排序

finalDic= {3:11, 2,9}

我已经尝试过了,甚至没有关闭我想要的

import collections

myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

def commonKey(x):
    i=0
    allKeys = []
    while i<len(x):
        for key in x[0].keys():
            allKeys.append(key)
        i=i+1
    commonKeys = collections.Counter(allKeys)
    commonKeys = [i for i in commonKeys if commonKeys[i]>len(x)-1]
    return commonKeys

print commonKey(myDic)

谢谢

4

4 回答 4

11

这是我的做法:

my_dict = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

# Finds the common keys
common_keys = set.intersection(*map(set, my_dict))

# Makes a new dict with only those keys and sums the values into another dict
summed_dict = {key: sum(d[key] for d in my_dict) for key in common_keys}

或者作为一个疯狂的单线:

{k: sum(d[k] for d in my_dict) for k in reduce(set.intersection, map(set, my_dict))}
于 2012-12-21T07:13:31.673 回答
2

只有一些指针:

  • 从每个目录中获取密钥,然后将它们转换为 set() 并计算 intersection() 或所有密钥集。这将为您提供公共密钥。
  • 现在迭代原始数据并总结每个字典的匹配值是直截了当的

实施留给 OP 作为练习。

于 2012-12-21T07:10:42.063 回答
1
l = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

new_dict = {}

def unique_key_value(a,b):
    return set(a).intersection(set(b))

def dict_sum(k, v):
    if k not in new_dict.keys():
        new_dict[k] = v
    else:
        new_dict[k] = new_dict[k] + v

for i in reduce(unique_key_value, l):
    for k in l:
        if i in k.keys():
            dict_sum(i, k[i])

print new_dict

希望这可以帮助。:)

于 2012-12-21T07:49:28.283 回答
1

蟒蛇3.2

from collections import defaultdict
c=defaultdict(list)
for i in myDic:
     for m,n in i.items():
            c[m].append(n)
new_dic={i:sum(v) for i,v in c.items()if len(v)==len(myDic)}
print(new_dic)
于 2012-12-21T14:45:35.977 回答