1

For example, I have a dictionary

dicts["A"] = 1
dicts["B"] = 2
dicts["C"] = 3 # .....etc, 

if I want to get the first 2 key, i.e."A" and "B" based on their values, i.e. 1 and 2, what should I do? Thanks in advance.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
zzzz
  • 55
  • 5
  • 3
    Choose another data structure because iterating the values of a dict to find something is not what they are build for. have a look at `dict.items()` and `dict.values()` functions of the dict – Patrick Artner Apr 06 '20 at 07:38
  • Does this answer your question? [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – dspencer Apr 06 '20 at 07:38
  • You may want to take a look at ``collections.Counter`` instead of a plain ``dict``. – MisterMiyagi Apr 06 '20 at 07:45

2 Answers2

1
dic={'A':1,'B':2, 'C': 3}
k = 2
[y[0] for y in sorted(dic.items(), key = lambda x: x[1])[:k]]

The last line sort the dictionary items according to the key (x[1]), then take the first k items ([:k]) and then extract only the keys (y[0]).

Tom Ron
  • 5,906
  • 3
  • 22
  • 38
0

Try:

#lets say
dic={'A':2,'B':1, 'C':5}
#sorting the dict
dic = {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}

Now that the dictionary is sorted, iterate through it. To find K smallest Values:

k = K
for i in range(k):
    print([k[0] for k in dic.items()][i])

Therefore, shortly:

k = K
for i in range(k):
    print([k[0] for k in {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}.items()][i])

As a One-Liner:

k = K
dic={'A':2,'B':1, 'C':5}
print('\n'.join([k[0] for k in {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}.items()][i] for i in range(k)))
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34