-2

Let's say I have a nested dictionary that looks like:

{ 'word1':
    {'VERB': 129}
    {'NOUN': 151}
    {'DET': 26426}
...
}

I want to get DET from the nested dict since it has the highest frequency. I tried to do it by iterating the dict[word1] but it seemed every inefficient. Is there an easy/simple way to do this?

Dawn17
  • 7,825
  • 16
  • 57
  • 118
  • 1
    Can you show us the code you have written so far and deemed inefficient? – jhansen Oct 26 '18 at 21:56
  • I don't think your solution is terribly inefficient. O(n) — where n == the number of keys you have for that word will probably be as efficient as you can get for finding the max, since these values aren't sorted and we don't want to resort to using any more storage. – LeKhan9 Oct 27 '18 at 00:04

2 Answers2

0

*Edited everything and gave more attention. Hope it helps.

list_of_keys = list(dictionary.keys())
list_of_values = list(dictionary.values())
max_value = max(list_of_values)
the_key = list_of_keys[list_of_values.index(max_value)]
0

You can try pandas:

import pandas as pd
dictionary = {'word1': {'VERB': 129, 'NOUN': 151, 'DET': 26426}, 'word2': {'VERB': 129, 'NOUN': 151, 'DET': 26476}}
df = pd.DataFrame(dictionary)
#       word1  word2
# DET   26426  26476
# NOUN    151    151
# VERB    129    129
df.apply(lambda row: row.max(), axis=1).idxmax()
# 'DET'

Or if you want something more concise:

pd.DataFrame(dictionary).apply(lambda row: row.max(), axis=1).idxmax()
# 'DET'

Hope this helps!

Pinyi Wang
  • 823
  • 5
  • 14