Related Articles

Related Articles

AttrDict module in Python
  • Last Updated : 18 Aug, 2020

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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"])

chevron_right


Output :

forGeeks
forGeeks

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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

Example 3 :Adding another dictionary to a dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :