Py学习  »  Python

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

Cookfishbro • 3 年前 • 1494 次点击  

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

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
 
1494 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Christopher Holley
Reply   •   1 楼
Christopher Holley    3 年前

你需要把裂缝去掉。这段代码生成您想要的示例。

customer_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]
            


for x in list(sorted_dict)[:3]:
    print(str(x) + ',' + str(sorted_dict[x]))
BrokenBenchmark
Reply   •   2 楼
BrokenBenchmark    3 年前

你的 for 循环在第一个匹配的值处停止。它不会为您的值找到所有匹配项。

没有必要创建单独的词典。可以根据值按降序对字典中的项进行排序,然后迭代排序过程的结果。

costumer_dict = {3:30, 1:22, 2:22}

for key, value in sorted(costumer_dict.items(), key=lambda x: x[1], reverse=True):
    print(f"{key},{value}")

这将产生:

3,30
1,22
2,22