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, ie "A"
and "B"
based on their values, ie 1 and 2, what should I do? Thanks in advance.
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)))
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]
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.