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
  • 309
  • 1
  • 7

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,113
  • 1
  • 7
  • 16
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,470
  • 1
  • 14
  • 21
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
  • 21,028
  • 6
  • 30
  • 43