Why is this python dictionary being created out of order with setdefault ()?

I am just starting to play with Python (background VBA). Why is this dictionary created out of order? Shouldn't it be: 1, b: 2 ... etc.?

class Card: def county(self): c = 0 l = 0 groupL = {} # groupL for Loop for n in range(0,13): c += 1 l = chr(n+97) groupL.setdefault(l,c) return groupL pick_card = Card() group = pick_card.county() print group 

here is the conclusion:

 {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12} 

or is it just printing out of order?

+6
source share
1 answer

Dictionaries have no order in python. In other words, when you iterate over a dictionary, the order in which the keys / elements “give way” is not the order you put into the dictionary. (Try using your code on a different version of python, and you will probably get a differently ordered output). If you want the dictionary that was ordered, you need collections.OrderedDict , which was not introduced before python 2.7. You can find equivalent recipes on ActiveState if you are using an older version of python. However, often this is good enough to just sort the elements (e.g. sorted(mydict.items()) .

EDIT as requested, example OrderedDict:

 from collections import OrderedDict groupL = OrderedDict() # groupL for Loop c = 0 for n in range(0,13): c += 1 l = chr(n+97) groupL.setdefault(l,c) print (groupL) 
+15
source

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


All Articles