【问题标题】:Iterate through the dictionary in alphabetical order [duplicate]按字母顺序遍历字典[重复]
【发布时间】:2021-06-05 19:55:36
【问题描述】:

我的 python 代码中有一个字典。我需要按排序键的顺序遍历它的所有元素。在 C++ 中,我这样做:

map<string, int> my_map;
my_map["ccc"] = 3;
my_map["aaa"] = 1;
my_map["bbb"] = 2;
for (auto item : my_map)
{
    cout << item.second << endl;
}

输出是:

1
2
3

但是如果我尝试在 python 中做类似的动作,输出顺序会发生变化:

my_dict = dict()
my_dict['ccc'] = 3
my_dict['aaa'] = 1
my_dict['bbb'] = 2
for item in my_dict.items():
    print(item[1])

输出是:

3
1
2

如何以与 c++ 中的 unordered_map 相同的顺序迭代 python 中的 dict?

【问题讨论】:

  • 试试for item in sorted(my_dict.items()):

标签: python


【解决方案1】:

在迭代之前先对项目进行排序:

for item in sorted(my_dict.items()):
    print(item[1])

【讨论】:

    【解决方案2】:
    for i in sorted(dict.items()):
       print(i)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 2023-03-04
      • 1970-01-01
      • 2018-01-27
      • 2015-04-07
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多