简体   繁体   English

如何遍历列表并按特定顺序打印密钥

[英]How to iterate through a list and print the key's in a specific order

I'm trying to print out the keys of my grocery list in the same order they are written in the dictionary originally, this only helps me print the keys alphabetically.我正在尝试按照最初在字典中写入的顺序打印我的购物清单的键,这只能帮助我按字母顺序打印键。

Here is my code currently:这是我目前的代码:

grocery_list = {
    "name": "milk",
    "cost": "2.99",
    "quantity": "2",
}

for i in sorted(grocery_list.keys()):
    print(grocery_list[i])

As stated in the comments, dictionaries were unordered containers, but recent python versions maintain insertion order so you can just do this for python3.6+ :正如评论中所述, dictionaries是无序的容器,但最近的python版本保持插入顺序,所以你可以只对python3.6+执行此python3.6+

grocery_list = {
    'name': 'milk',
    'cost':'2.99',
    'quantity':'2'
}

for key, value in grocery_list.items():
   print(key, value, sep=': ')

>>> name: milk
>>> cost: 2.99
>>> quantity: 2

If you run an older python version, you have to somehow specify order, in this case is manual:如果您运行较旧的python版本,则必须以某种方式指定顺序,在这种情况下是手动的:

ordered_keys = ['name', 'cost', 'quantity']

for key in ordered_keys:
    print(key, grocery_list[key], sep=': ')

>>> name: milk
>>> cost: 2.99
>>> quantity: 2

键以任意顺序返回,参考此链接可能会有所帮助。

You can choose to use OrderedDict.您可以选择使用 OrderedDict。

from collections import OrderedDict

d1 = OrderedDict({
    'name': 'milk',
    'cost': '2.99',
    'quantity': '2'
})
print(d1.keys())

For versions 3.6+, simply use grocery_list.keys() to get all the keys of your dictionary.对于 3.6+ 版本,只需使用grocery_list.keys()即可获取字典的所有键。 It returns dict_keys(['name', 'cost', 'quantity']) For older versions, you can use OrderedDict .它返回dict_keys(['name', 'cost', 'quantity'])对于旧版本,您可以使用OrderedDict This will retain the order of your dictionary.这将保留字典的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM