python One of the common data structures is a dictionary , About the traverse , Insert , Delete . Common, such as using items(),update,pop etc. . Use when indexing keys().
>>> dic = dict(key='value')
>>> dic
{
'key': 'value'}
>>> dic['key']
'value'
>>> dic.get('key')
'value'
In the past, most of the usage was to use [‘key’] perhaps get To visit in the form of , because get For the nonexistent key Can return None, But if a dictionary doesn't exist key Use [‘key’] Will prompt key Wrong question . So if you want to use the traditional method to scope the dictionary , It is recommended to use dict.get(‘key’) In the form of
>>> dic['name']
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'name'
>>> dic.get('name')
If you can use objects . Property to access , It can greatly simplify the red tape of access . Here is a library for dictionary operation and access much
python -m pip install munch
Use instance Determine the instance type and dictionary access
from munch import Munch
dicMu = Munch()
print(isinstance(dicMu , dict))
dicMu .key = 'value'
print(f' Output dic["key"] form : {
dicMu ["key"]}')
print(f' Output dic.get("key") form : {
dicMu .get("key")}')
print(f' Output dic.key form : {
dicMu .key}')
Output is as follows :
True
Output dic["key"] form : value
Output dic.get("key") form : value
Output dic.key form : value
because Munch Class inherited from dict, So subclass Munch Applicable to parent class dict General operation of dictionary . It can be used for addition, deletion, modification and query
from munch import Munch
dicMu = Munch()
dicMu.name = 'zhiyu'
dicMu['age'] = 'NN'
print(f' The original dictionary : {
dicMu}')
# Add elements
dicMu['gender'] = 'big man'
dicMu.name2 = 'zhiyu2'
print(f' Dictionary inserts data : {
dicMu}')
# Modifying elements
dicMu['gender'] = 'modifyMan'
dicMu.name2 = 'modifyName'
print(f' The dictionary modifies the data : {
dicMu}')
# Remove elements
dicMu.pop('gender')
print(f' Dictionary delete data : {
dicMu}')
Output is :
The original dictionary : Munch({
'name': 'zhiyu', 'age': 'NN'})
Dictionary inserts data : Munch({
'name': 'zhiyu', 'age': 'NN', 'gender': 'big man', 'name2': 'zhiyu2'})
The dictionary modifies the data : Munch({
'name': 'zhiyu', 'age': 'NN', 'gender': 'modifyMan', 'name2': 'modifyName'})
Dictionary delete data : Munch({
'name': 'zhiyu', 'age': 'NN', 'name2': 'modifyName'})
Of course, deleting data can also be used
del dicMu['name2']
del dicMu.name2
In addition, some other methods of dictionary are also applicable , Such as traversal method dicMu.items(),dicMu.keys(),dicMu.vaules(),dicMu.setdefault(‘gender’, ‘male’) And so on .
from munch import Munch
dicMu = Munch()
dicMu.name = 'zhiyu'
dicMu['age'] = 'NN'
print(f' The original dictionary : {
dicMu}')
print(dicMu.get('gender'))
print(dicMu.get('gender'), 'none data')
dicMu.setdefault('gender', 'male')
print(dicMu.get('gender'))
Another way is to use Munch Medium DefaultMunch, The function is similar to setdefault Visit nonexistent key when , Returns a specified default value . And you can specify the default value of multiple data , Instead of using get equally , Set each one , Or use setdefault Set it up
from munch import DefaultMunch
dicMu = DefaultMunch('undefined', {
'name':'zhiyu'})
print(dicMu)
print(dicMu.age)
print(dicMu.gender)
Output is :
DefaultMunch('undefined', {
'name': 'zhiyu'})
undefined
undefined
The above access does not exist key when , Return to the specified prompt that there is no data , If not age, visit age Prompt when undefined. Another situation is if there is no such key, Add a new one to the dictionary key value . By visiting Munch Object does not exist key when , Automatically trigger to Munch Object adds a new key And set a default value for it , You need to use... At this time DefaultFactoryMunch function .
from munch import DefaultFactoryMunch
dicMu1 = DefaultFactoryMunch(list, {
'name':'zhiyu'})
print(dicMu1.age)
dicMu2 = DefaultFactoryMunch(dict, {
'name':'zhiyu'})
print(dicMu2.age)
dicMu3 = DefaultFactoryMunch(tuple, {
'name':'zhiyu'})
print(dicMu3.age)
print(dicMu3)
dicMu3.age = 'NN'
print(dicMu3)
dicMu4 = DefaultFactoryMunch('undefined', {
'name':'zhiyu'})
DefaultFactoryMunch(tuple, {
'name': 'zhiyu', 'age': 'NN'})
print(dicMu4.age)
Output is as follows :
[]
{
}
Traceback (most recent call last):
DefaultFactoryMunch(tuple, {
'name': 'zhiyu', 'age': ()})
File "D:\python37\lib\site-packages\munch\__init__.py", line 103, in __getattr__
return object.__getattribute__(self, k)
AttributeError: 'DefaultFactoryMunch' object has no attribute 'age'
self[k] = self.default_factory()
TypeError: 'str' object is not callable
Find out if you use DefaultFactoryMunch Cannot be used not callable object .
Munch Support serialization into Json perhaps yaml Format string to Json object .
from munch import Munch
import json
import yaml
munch_obj = Munch(foo=Munch(lol=True), bar=100, msg='hello')
print(json.dumps(munch_obj))
munch_obj = Munch(foo=Munch(lol=True), bar=100, msg='hello')
print(yaml.dump(munch_obj))