1

I have a dict like:

example = {'a':2, 'b':2, 'c':1, 'd':1}

I want to keep only the maximum values and keys. The output should be:

{'a':2, 'b':2}

This is different from just getting the maximum value, as has been asked in other places. What is the best way to do this?

Charles
  • 329
  • 1
  • 9

3 Answers3

4

This is one way to do this:

{k:v for k,v in example.items() if v == max(example.values())}

>>>

{'a': 2, 'b': 2}
user6386471
  • 1,203
  • 1
  • 8
  • 17
0

Since you tagged this question with pandas I suggest the following:

s = pd.Series(example)
s[s == s.max()].to_dict()

>>> {'a': 2, 'b': 2}
Mateo Torres
  • 1,545
  • 1
  • 13
  • 22
0

something like

example = {'a':2, 'b':2, 'c':1, 'd':1}
filtered = {k:v for k,v in example.items() if v == max(example.values())}
print(filtered)

output

{'a': 2, 'b': 2}
balderman
  • 22,927
  • 7
  • 34
  • 52