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.
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.
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]
).
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)))