【问题标题】:Iterating over dictionary keys in order?按顺序迭代字典键?
【发布时间】:2021-05-26 04:17:37
【问题描述】:

我正在尝试迭代一个字典(特别是在另一个字典中,但我认为这部分并不重要),并且我无法让 for 循环按照它们被放置的顺序迭代这些值在。我希望能够获取每个字典的第一个值。我认为在 python 3.6 之后,字典保持了它们的顺序 (here),但这些不会保持顺序。

这就是我的字典的样子:

count_dict = {'dessert': Counter({'cake': 1}), 'vegetable': Counter({'carrots': 1, 'beet': 1}), 'grain': Counter({'wheat': 3, 'rice': 2, 'zantham': 1}), 'meat': Counter({'chicken': 2, 'pork': 1})}

这是我尝试过的代码:

for it in count_dict:
        for food in count_dict[it]:
            out_dict[it] = food
return(out_dict)

我明白了:

{'dessert': 'cake', 'vegetable': 'beet', 'grain': 'rice', 'meat': 'chicken'}

但需要从每个字典中获取第一个值:

{'dessert': 'cake', 'vegetable': 'carrots', 'grain': 'wheat', 'meat': 'chicken'}

我一直在 Stack 上寻找答案,但找不到答案。 (对不起,如果答案很明显,我对 Python 有点陌生)

【问题讨论】:

  • 请注意,您的实际输出和预期输出具有相同的按键顺序。这就是保留顺序的含义:键保持相同的顺序。显然,在这种情况下,counter 使用的字典不会保持它们的顺序。
  • beet 不是第一个值,但你说你想要第一个值。

标签: python python-3.x


【解决方案1】:

字典(python 3.6 之后)维护它们的插入顺序(键和值的插入顺序),而不是排序顺序。


我确实得到了答案。

from collections import Counter

count_dict = {'dessert': Counter({'cake': 1}), 'vegetable': Counter({'carrots': 1, 'beet': 1}), 'grain': Counter({'wheat': 3, 'rice': 2, 'zantham': 1}), 'meat': Counter({'chicken': 2, 'pork': 1})}

new_dict = {}

for a, b in count_dict.items():
    new_dict[a] = sorted(b, key=lambda x: (-b[x], x))[0]

print(new_dict)

这将首先按值排序内部字典,然后按字母顺序按键。

sorted(b, key=lambda x: (-b[x], x))

样本运行 1(按字母顺序排序,因为值相同。)

b = {'carrots': 1, 'beet': 1}
sorted(b, key=lambda x: (-b[x], x))

输出

['beet', 'carrots']

Sample Run 2(按值和字母顺序排序。)

b = {'wheat': 3, 'rice': 2, 'zantham': 1}
sorted(b, key=lambda x: (-b[x], x))

输出

['wheat', 'rice', 'zantham']

【讨论】:

  • 谢谢,我脑子里有这个,但不知道该怎么做。很抱歉要求更多,但是 (-b[x]), x) 部分如何在 lambda 函数中工作?
  • b[x] 为键 x 提供值。 sorted 将按值的升序对其进行排序。当我们将其更改为-b[x] 时,最大值将是最小值。所以我们将按值倒序排列。您可以说我们为什么不使用reverse 参数,但我们也希望它按字母顺序按键排序。如果两个键的值相同,则sorted 将检查键x 并根据键x 对其进行排序。
【解决方案2】:

如果您只想返回 first 键值,而不管字母键顺序或数值顺序如何,您可以简单地执行以下操作:

from collections import Counter

count_dict = {'dessert': Counter({'cake': 1}), 'vegetable': Counter({'carrots': 1, 'beet': 1}), 'grain': Counter({'wheat': 3, 'rice': 2, 'zantham': 1}), 'meat': Counter({'chicken': 2, 'pork': 1})}
out_dict = {}

for it in count_dict:
        for food in count_dict[it]:
            out_dict[it] = food
            break  # Break out the loop so that you only iterate over the first key in dictionary
print(out_dict)

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2015-01-04
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多