Collections in Python Ordereddict() usage

Time:2022-1-13

Dictionary objects in Python can access data in the form of “key: value”. Ordereddict is a subclass of it, which implements the sorting of elements in dictionary objects.

Note that the keys of ordereddict are arranged in the order of insertion, not the key itself:

For example, the following compares the differences between the two methods:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import collections
print 'Regular dictionary:'
d={}
d['a']='A'
d['b']='B'
d['c']='C'
for k,v in d.items():
    print k,v
 
print '\nOrderedDict:'
d=collections.OrderedDict()
d['a']='A'
d['b']='B'
d['c']='C'
for k,v in d.items():
    print k,v

The output results are as follows:

Regular dictionary:
a A
c C
b B
 
OrderedDict:
a A
b B
c C

You can see that the three ABC elements are also saved, but using ordereddict will sort according to the order in which the elements are placed.

Due to sorting, if the order of the dictionary objects of ordereddict objects is different, python will treat them as two different objects, such as the following code:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import collections
print 'Regular dictionary:'
d1={}
d1['a']='A'
d1['b']='B'
d1['c']='C'
 
d2={}
d2['c']='C'
d2['a']='A'
d2['b']='B'
 
print d1==d2
print '\nOrderedDict:'
d1=collections.OrderedDict()
d1['a']='A'
d1['b']='B'
d1['c']='C'
 
d2=collections.OrderedDict()
d2['c']='C'
d2['a']='A'
d2['b']='B'
 
print  d1==d2

The output result is:

Regular dictionary:
True
 
OrderedDict:
False

Supplement: Python collections Ordereddict solves the problem of the order of dict elements

There is a problem in programming, python JSON The order of elements may change when loading.

This is fatal for some code that needs to use element order to do some strategy.

Check it online and summarize it with your own knowledge.

When using dict, keys are unordered. When iterating over dict, we cannot determine the order of keys.

If you want to maintain the order of keys, you can use ordereddict.

The keys of ordereddict are arranged in the order of insertion, not the key itself.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#coding=utf-8
import json
import collections
my_dict = {}
my_list = ["Test", "1324", "r4ge5"]
 
for i in my_list:
   my_dict[i] = my_list[my_list.index(i)]
print STR1 original string:
str1 = json.dumps(my_dict, ensure_ascii=False)
print str1
print Result of loading STR1 string:
data_js = json.loads(str1)
print json.dumps(data_js, ensure_ascii=False).encode("utf8")
 
print "Result of loading STR1 string (using ordereddict):"
data_js = json.loads(str1, object_pairs_hook=collections.OrderedDict)
print json.dumps(data_js, ensure_ascii=False).encode("utf8")

Execution results:

STR1 original string:
{“test”: “test”, “r4ge5”: “r4ge5”, “1324”: “1324”}
Results of loading STR1 string:
{“r4ge5”: “r4ge5”, “1324”: “1324”, “test”: “test”}
Result of loading STR1 string (using ordereddict):
{“test”: “test”, “r4ge5”: “r4ge5”, “1324”: “1324”}

The above is my personal experience. I hope I can give you a reference, and I hope you can support developepper.

Recommended Today

Servlet web container in springboot

1. Preface Springboot supports embeddedServletContainer: SpringBoot 2.0.3. Release requires Java 8 or 9 and spring framework 5.0.7 Release or later. Provides explicit build support for Maven 3.2 + and gradle 4. 2. Use Tomcat Springboot defaultServletContainer isTomcat, no additional configuration is required, just importspring-boot-starter-webDependence. <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> Start the application and run […]