Wednesday, July 3, 2024
HomeLanguagesPythonAttrDict module in Python

AttrDict module in Python

AttrDict is an MIT-licensed library which provides mapping objects that allow their elements to be accessed both as keys and as attributes.
 So we can think of the dictionary that we import and use.

Installation: 

To install AttrDict, use the pip command as follows:

pip install attrdict

Having installed it, let us understand it with the working of a program:

Example 1 :Here we will show how to create a dictionary pair using the module.

Python3




# importing the module
from attrdict import AttrDict
 
# creating a dictionary pair
dictionary = AttrDict({"Geeks" : "forGeeks"})
 
# accessing the value using key
# method 1
print(dictionary.Geeks)
 
# method 2
print(dictionary["Geeks"])


Output :  

forGeeks
forGeeks

Example 2 :Making a Nested dictionary of multiple elements and printing them. 

Python3




# importing the module
from attrdict import AttrDict
 
# creating a dictionary
dictionary = AttrDict({'foo': 'bar',
                       'alpha': {'beta': 'a',
                                 'a': 'a'}})
 
# printing the values
for key in dictionary:
    print(dictionary[key])


Output : 

bar
{'beta': 'a', 'a': 'a'}

Example 3 :Adding another dictionary to a dictionary.

Python3




# importing the module
from attrdict import AttrDict
 
# creating the first dictionary
a = {'foo': 'bar', 'alpha': {'beta': 'a', 'a': 'a'}}
 
# creating the second dictionary
b = {'lorem': 'ipsum', 'alpha': {'bravo': 'b', 'a': 'b'}}
 
# combining the dictionaries
c = AttrDict(a) + b
 
print(type(c))
print(c)


Output : 

<class 'attrdict.dictionary.AttrDict'>
AttrDict({'foo': 'bar', 'lorem': 'ipsum', 'alpha': {'beta': 'a', 'bravo': 'b', 'a': 'b'}})

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments