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+
:
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:
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.
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. It returns dict_keys(['name', 'cost', 'quantity'])
For older versions, you can use OrderedDict
. This will retain the order of your dictionary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.