Py学习  »  Python

Python:如何完整地打印出字典的前n个键和值

Cookfishbro • 3 年前 • 1385 次点击  

我想用从大到小排序的值打印键和值

costumer_dict = {3:30, 1:22, 2:22}
sorted_values = [30, 22, 22]
sorted_dict = {}

for i in sorted_values:
        for k in customer_dict.keys():
            if customer_dict[k] == i:
                sorted_dict[k] = customer_dict[k]
                break

for x in list(sorted_dict)[:3]:
    print(str(x) + ',' + str(sorted_dict[x]))

我期待的答案是

3,30
1,22
2,22

但它只会打印出来

3,30
1,22

但是如果字典中没有重复的值,它会打印出正确的答案,所以我想知道为什么会发生这种情况。 我是python的初学者,有人能告诉我代码哪里错了吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133539
 
1385 次点击  
文章 [ 2 ]  |  最新文章 3 年前