• notice
  • Congratulations on the launch of the Sought Tech site

Convert dictionary to member variable in Python

technical background

When we write a class in Python, if some member variables need to be named and assigned with a dictionary, what should we do at this time? This scenario is most common in reading dictionary variables from a file (such as json, npz, etc.) into memory, and then assigning them to member variables of a class, or instance variables that have been generated.

Use __dict__ to define member variables

This method is directly supported in python __dict__.update()to avoid the use of locals(), vars() and eval() functions. We can directly look at such a case:

In [ 1 ]: dict_a = { 'a' : 1 , 'b' : 2 }
 In [ 2 ]: dict_b = { 'c' : 3 }
 In [ 3 ]: class D ( object ):
    ...: def __init__(self):
 ...: self.d = 4 ...: self.__dict__.update(dict_a)
    ...: self.__dict__.update(dict_b)
 In[4]: new_D = D()
 In[5]: new_D.__dict__


5 ]: { 'd' : 4 , 'a' : 1 , 'b' : 2 , 'c' : 3 }
 In [ 6 ]: new_D.a
 Out[ 6 ]: 1 In [ 7 ]: new_D.c
 Out[ 7 ]: 3

dict_aIn this case, we define two dictionaries and outside the class, and dict_bthe keys of the dictionaries are all in the format of strings. And we know that the string format cannot be used directly as a variable name in python if eval is not used. After the dictionary is imported through __dict__.update()the method, all the key and value values in it will be automatically recognized, and then assigned to the current class as member variables. However, this method has a disadvantage that it can only be assigned through a single-layer dictionary. If a dictionary with a hierarchical structure is encountered, it will not automatically distinguish the hierarchical structure for assignment, such as the following code:

In [ 15 ]: dict_a = { 'f' :{ 'h' : 8 }, 'g' : 7 }
 In[16]: new_D = D()
 In[17]: new_D.__dict__
 Out[ 17 ]: { 'd' : 4 , 'f' : { 'h' : 8 }, 'g' : 7 , 'c' : 3 }

Nested dictionary to member variable

According to the special scenario mentioned at the end of the previous chapter, we need to recurse the elements in the dictionary. If we encounter a nested dictionary element, we will recursively add the element to the member variable of the next level. The specific code As follows:

dict_a = { 'f' :{ 'h' : 8 }, 'g' : 7 }
 dict_b = { 'c' : 3 }
 class D :
 def __init__ ( self, *args ):
 for arg in args:
 for k, v in arg.items():
 if isinstance (v, dict ):
                     self.__dict__[k] = D(v)
 else :
                     self.__dict__[k] = v
 new_D = D(dict_a, dict_b)


The final output is as follows:

{ 'f' : <__main__.D object at 0x7fd2f32a4340>
 , 'g' : 7, 'c' : 3}

It can be seen that the method we finally passed new_D.f.hsuccessfully read the value in the original nested dictionary. While this doesn't seem very elegant, there doesn't seem to be a better solution. And, through the practice of this small problem, I found another slightly interesting problem: when updating the dictionary type in python, if the key string contains a dot, for example parDict['group1.b'] = 3, it can only be done in the form of such a string Update, if you use parDict.update(group1.b=4)it, an error will occur. This is because the dot is not an identifier in python and cannot be used for naming. The original text is as follows:

The valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.

Summary summary

The problem scenario solved in this article is as follows: if a dictionary is given, for example, the data generally loaded from a json file or an npz file is a dictionary data structure, if we want to assign this dictionary to a class, and make the dictionary The key and value are respectively used as the member variable name and member variable value of the class, so how to achieve it? For a flattened dictionary (without nested dictionaries), we can directly use update to convert all keys and values in the dictionary into member variables of the current class. What is more troublesome is the hierarchical structure dictionary containing nested dictionaries. At this time, we can only use loops and recursively assign values to the member variables of the class.


Technical otaku

Sought technology together

Related Topic


Leave a Reply