如何在dict列表中找到公共键并按值排序?

2024-10-01 00:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个finalDic,它包含公共键及其值的和

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

首先找到公共密钥

^{pr2}$

然后根据它们的值求和排序

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)

谢谢


Tags: keyinimportforlen排序def密钥
3条回答

只有一些提示:

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

作为一个练习,这个实现留给了OP。在

我是这样做的:

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}

或者是疯狂的一句话:

^{pr2}$
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

希望这有帮助。:)

相关问题 更多 >