2

I have a dictionary which looks like this:

bigdict = { 

'a': {'foo':2, 'bar':3, 'baz':7, 'qux':1},
'b': {'foo':6, 'bar':4, 'baz':3, 'qux':0},
'c': {'foo':4, 'bar':5, 'baz':1, 'qux':6}
}

And for each dictionary, I want to be able to grab the 2 keys with the highest values and put the results in a new dictionary.

e.g.

newbigdict = {
 a: {'baz':7, 'bar':3},
 b: {'foo': 6, 'bar':4},
 c: {'qux':6, 'bar':5}
}

Any ideas? I've been stuck on this for a while. I use Python 3.

rrao
  • 629
  • 4
  • 13
Jack Levent
  • 75
  • 1
  • 5
  • Related [Getting key with maximum value in dictionary?](http://stackoverflow.com/q/268272) and [5 maximum values in a python dictionary](http://stackoverflow.com/q/7197315) – Bhargav Rao Jun 04 '16 at 14:40
  • Apply solution of question linked by @BhargavRao. Remove key from dict. Apply again. – spectras Jun 04 '16 at 14:44
  • @spectras Or sort the dict and take the top two. It's simpler and works better in case the OP needs to save the original dict. – Bhargav Rao Jun 04 '16 at 15:12

2 Answers2

1

This can be solved easily using a dictionary comprehension. See this post for more explanation about a Python Dictionary Comprehension

>>> def findtoptwo(d):
...     toptwo = sorted(d.values())[-2:]
...     return {k:v for k,v in d.items() if v in toptwo}
... 
>>> newdict = {k:findtoptwo(v) for k,v in bigdict.items()}
>>> newdict
{'a': {'bar': 3, 'baz': 7}, 'c': {'qux': 6, 'bar': 5}, 'b': {'foo': 6, 'bar': 4}}

The logic here is simple, For each key-value pair in the dictionary we check if the value is present in the top two values. For this we sort the dictionary values and slice the last two values. Read more about slices in python here and the builtin sorted here.

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

it can be done pretty easily using pandas module:

In [97]: bigdict = {
   ....: 'a': {'foo':2, 'bar':3, 'baz':7, 'qux':1},
   ....: 'b': {'foo':6, 'bar':4, 'baz':3, 'qux':0},
   ....: 'c': {'foo':4, 'bar':5, 'baz':1, 'qux':6},
   ....: }

In [98]: df = pd.DataFrame.from_dict(bigdict)

In [99]: df
Out[99]:
     a  b  c
bar  3  4  5
baz  7  3  1
foo  2  6  4
qux  1  0  6

In [126]: df.apply(lambda x: x.nlargest(2).to_dict()).to_dict()
Out[126]:
{'a': {'bar': 3, 'baz': 7},
 'b': {'bar': 4, 'foo': 6},
 'c': {'bar': 5, 'qux': 6}}

one-liner:

In [129]: (pd.DataFrame.from_dict(bigdict)
   .....:    .apply(lambda x: x.nlargest(2).to_dict())
   .....:    .to_dict()
   .....: )
Out[129]:
{'a': {'bar': 3, 'baz': 7},
 'b': {'bar': 4, 'foo': 6},
 'c': {'bar': 5, 'qux': 6}}
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419