Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 941
bekman Avatar asked Dec 21 '12 07:12

bekman


People also ask

How do I sort a list of dictionaries by key?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

Can you sort a list of dictionaries in Python?

We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.

How do you get the keys of a dictionary in a list?

Method 1: Get dictionary keys as a list using dict. The dict. keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.


1 Answers

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))}
like image 150
Blender Avatar answered Sep 25 '22 15:09

Blender