How to find common keys in a list of dicts and sort them by value?

大憨熊 提交于 2020-01-24 07:28:22

问题


I want to create a finalDic which contains common keys and sum of their values

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

First find common keys

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

Then Sum and sort by their values

finalDic= {3:11, 2,9}

I've tried this and not even close what i want

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)

Thanks


回答1:


Here's how I'd do it:

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}

Or as a crazy one-liner:

{k: sum(d[k] for d in my_dict) for k in reduce(set.intersection, map(set, my_dict))}



回答2:


Only some pointers:

  • obtain the keys from each directory in turn them into a set() and calculate the intersection() or all key sets. This will give you the common keys.
  • now iterating over the original data and summing up the matching values from each dict is straight forward

The implementation is left to the OP as an exercise.




回答3:


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

hope this helps. :)




回答4:


python 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)


来源:https://stackoverflow.com/questions/13985686/how-to-find-common-keys-in-a-list-of-dicts-and-sort-them-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!