Here's a summary of how to achieve the following in Python's dict
.
Example
d.a = 1
This can be achieved with ʻattrdict.AttrDict`.
$ pip install attrdict
This can be achieved with collections.OrderedDict
.
If you write as follows, the order will not be maintained.
Bad example
# coding=utf-8
import collections
#Main processing
if __name__ == '__main__':
#If you give an element as an argument and perform initialization, the order is not preserved
d = collections.OrderedDict(a=1, b=2, c=3, d=4)
#Display d key and value in order
for k, v in d.items():
print('{} : {}'.format(k, v))
Therefore, if you want to initialize it, you need to make it a tuple as follows.
Good example
# coding=utf-8
import collections
#Main processing
if __name__ == '__main__':
#If you give an element as a tuple and perform initialization, the order is preserved
d = collections.OrderedDict((('a', 1), ('b', 2), ('c', 3), ('d', 4)))
#Display d key and value in order
for k, v in d.items():
print('{} : {}'.format(k, v))
Recommended Posts