-1

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])
Henry Woody
  • 14,024
  • 7
  • 39
  • 56
Patryk100
  • 19
  • 1
  • 5
  • 2
    [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) – Jab Feb 04 '20 at 01:11
  • No, what I'm trying to achieve is printing name, cost, quantity in that order. – Patryk100 Feb 04 '20 at 01:16
  • 1
    Stop using sorted. Python 3.6+ retains insertion order of dicts so unless you’re on and older version you’re sorting when you shouldn’t be for this case otherwise use OrderedDict. – Jab Feb 04 '20 at 01:19
  • This looks like a duplicate of https://stackoverflow.com/q/1867861/11301900. – AMC Feb 04 '20 at 04:25
  • Does this answer your question? [How to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared) – Phoenix Feb 04 '20 at 05:23

4 Answers4

1

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
marcos
  • 4,473
  • 1
  • 10
  • 24
  • To be pedantic: this is only guaranteed on python 3.7 and beyond. The fact that it works on the 3.6 version of cpython is an implementation detail, and it is not guaranteed that every implementation of python 3.6 will behave this way. – SethMMorton Feb 04 '20 at 02:42
  • @SethMMorton that's totally true! – marcos Feb 04 '20 at 02:48
0

The keys are returned in arbitrary order, may be helpful to refer to this link.

de_classified
  • 1,927
  • 1
  • 15
  • 19
0

You can choose to use OrderedDict.

from collections import OrderedDict

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

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.

Swati Srivastava
  • 1,102
  • 1
  • 12
  • 18