Differences ordered dictionary with the ordinary dictionary

Difference python ordered dictionary with the ordinary dictionary

Recent django used in the orderly development of the dictionary, so study a little, or less.

Example:

Typically dictionary ordered dictionary and the like, but it can record the sequence in which the inserted element, and the dictionary will generally arbitrary order iteration.

Ordinary dictionary:

1 d1={}
2 d1['a']='A'
3 d1['b']='B'
4 d1['c']='C'
5 d1['d']='D'   #此时的d1 = {'a':'A','b':'B','c':'C','d':'D'}
6 for k,v in d1.items():
7     print k,v

The output is:

1 a A
2 c C
3 b B
4 d D

As can be seen from the results of the above ordinary dictionary is traversed output is disordered.

The following is an ordered dictionary (need to import collections package):

1 import collections
2 d1={}
3 d1=collections.OrderedDict()  #将普通字典转换为有序字典
4 d1['a']='A'
5 d1['b']='B'
6 d1['c']='C'
7 d1['d']='D'
8 for k,v in d1.items():
9     print k,v

The output is:

1 a A
2 b B
3 c C
4 d D

Comparison of the two outputs, not difficult to find, ordered dictionary dictionary insertion order can be output element .

The reason why the above two examples dictionary insert elements, rather than a good dictionary will start element definition, because the role of an ordered dictionary just to remember the order of insertion elements and sequentially output.

If the order of elements in the dictionary definition of a good start, the elements behind this action is not inserted, then traverse ordered dictionary, its output is empty, because the lack of an orderly insertion of this condition, so in this case ordered dictionary will lose its effect, so ordered dictionary is generally used to dynamically add and when required by the order of addition output .

for example:

1 import collections
2 d2 = {'a':'A','b':'B','c':'C','d':'D'}
3 d2=collections.OrderedDict()  #将普通字典转换为有序字典
4 for k,v in d2.items():
5     print k,v

Its output is null.

Guess you like

Origin www.cnblogs.com/g15009428458/p/11605217.html