How to achieve access by attribute and retention of insertion order in Python dict

Here's a summary of how to achieve the following in Python's dict.

Example


d.a = 1

Object to realize

Access by attribute only

This can be achieved with ʻattrdict.AttrDict`.

Installation method

$ pip install attrdict

Access by attribute and retention of insertion order

This can be achieved with collections.OrderedDict.

Precautions for initialization

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))

Former story

References

Recommended Posts

How to achieve access by attribute and retention of insertion order in Python dict
[Python] How to sort dict in list and instance in list
How to store Python function in Value of dictionary (dict) and call function according to Key
Comparison of how to use higher-order functions in Python 2 and 3
How to access environment variables in Python
How to use is and == in Python
Summary of how to import files in Python 3
Summary of how to use MNIST in Python
How to plot autocorrelation and partial autocorrelation in python
How to get the number of digits in Python
[Python] How to output the list values in order
How to develop in Python
How to swap elements in an array in Python, and how to reverse an array.
[python] Summary of how to retrieve lists and dictionary elements
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
Reference order of class variables and instance variables in "self. Class variables" in Python
[Python] Summary of how to use split and join functions
How to develop in a virtual environment of Python [Memo]
How to get a list of built-in exceptions in python
How to execute external shell scripts and commands in python
How to log in to AtCoder with Python and submit automatically
Overview of Python virtual environment and how to create it
How to create an instance of a particular class from dict using __new__ () in python
[Python] How to delete rows and columns in a table (list of drop method options)
[Super easy! ] How to display the contents of dictionaries and lists including Japanese in Python
How to check if the contents of the dictionary are the same in Python by hash value
[Python] How to do PCA in Python
How to determine the existence of a selenium element in Python
How to install OpenCV on Cloud9 and run it in Python
How to know the internal structure of an object in Python
How to collect images in Python
How to use SQLite in Python
How to check the memory size of a variable in Python
[Python] How to get the first and last days of the month
How to use functions in separate files Perl and Python versions
How to check the memory size of a dictionary in Python
Difference in how to write if statement between ruby ​​and python
Make Python dict accessible by Attribute
How to use Mysql in python
[ROS2] How to describe remap and parameter in python format launch
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to access wikipedia from python
Convert the result of python optparse to dict and utilize it
How to handle Japanese in Python
How to display bytes in the same way in Java and Python
How to put OpenCV in Raspberry Pi and easily collect images of face detection results with Python
[Python Kivy] How to get the file path by dragging and dropping
How to resolve "No kernel of grammar Python found" error in Atom
How to write the correct shebang in Perl, Python and Ruby scripts
How to send a visualization image of data created in Python to Typetalk
How to get the date and time difference in seconds with python
[Python] How to put any number of standard inputs in a list
How to put a half-width space before letters and numbers in Python.
I tried to verify and analyze the acceleration of Python by Cython
Implementation of particle filters in Python and application to state space models
How to format a list of dictionaries (or instances) well in Python
How to sort by specifying a column in the Python Numpy array.
How to stop a program in python until a specific date and time
How to deal with old Python versions in Cloud9 made by others