Like keys selected in a dictionary during iteration in Python

my_dict = {'a':10, 'b':20, 'c':30}

for key in my_dict:
    print key, my_dict[key]

gives

a 10
c 30
b 20

and

my_dict = {'a':10, 'c':30, 'b':20}

for key in my_dict:
    print key, my_dict[key]

gives the same result

a 10
c 30
b 20

I was wondering why this is not an option, like 10 b 20 c 30. How are the keys selected during iteration through the dictionary? Is it random?

+4
source share
4 answers

The keys () method of the dictionary object returns a list of all the keys used in the dictionary in random order (if you want it sorted, just apply the sorted () function to it). To check if one key is in the dictionary, use the keyword.

The order of the keys in is dict()not defined (depending on which Python implementation you are using). To iterate through a dict in an ordered manner:

my_dict = {'a': 10, 'b': 20, 'c': 30}
for key in sorted(my_dict.keys()):
    print key, my_dict[key]

:

a 10
b 20
c 30

, , , dict() - , , . , . SO

+2
+2

Python . , .

, , sorted:

>>> my_dict = {'a':10, 'c':30, 'b':20}
>>> for key in sorted(my_dict):
...     print key, my_dict[key]
... 
a 10
b 20
c 30
+1

, :

for key in sorted(my_dict.keys()):
    print '{0} {1}'.format(key, my_dict.get(key))

This gives:

a 10
b 20
c 30
0
source

Source: https://habr.com/ru/post/1620268/


All Articles