I have a dict that looks something like this:
ip = { "1" : ['a','b'], "2" : ['a','c'], "3" : ['a','b','c','d'], "4" : ['a','b','d','e']}
I need to find which of the elements in the sets of values have the maximum number of keys against them, as well as the elements listed in descending order. The result will be something like this:
op = {"a":4,"b":3,"c":2,"d":2,"e":1}
But I read somewhere that a dict cannot be sorted, so the output can also be a tuple:
op = [('a', 4), ('b', 3), ('c', 2), ('d', 2), ('e', 1)]
We can iterate through the dict and for each of the elements in the given value, the result is incremented in defaultdict for this element.
op = defaultdict(int) for k,v in ip.iteritems(): for item in v: op[item]+=1 op = sorted(op.items(), key=lambda x: x[1], reverse=True)
Is there a faster / better way to do this than a nested one?