【发布时间】: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