Dictionary in Python:
A Python dictionary is a list of objects that are not in any particular order i.e Unordered.
A dictionary is made up of a collection of key-value pairs. Each key-value pair corresponds to a specific value.
Curly braces { } can be used to describe a dictionary by enclosing a comma-separated list of key-value pairs.
Every key is separated from its associated value by a colon “:”
collections.UserDict() Function:
Python has a dictionary-like container called UserDict, which is available in the collections module. This class serves as a container for dictionary objects. This class is useful when one wants to create their own dictionary, either with modified or new functionality. It can be thought of as a method of adding new behaviors to the dictionary. This class takes a dictionary instance as an argument and simulates the contents of a regular dictionary. This class’s data attribute provides access to the dictionary.
Syntax:
collections.UserDict([initial data])
Python Program for collections.UserDict() Function
Method #1: Using collections Module (Static Input)
Approach:
- Import UserDict() function from the collections module using the import keyword.
- Give the dictionary as static input and store it in a variable.
- Pass the given dictionary as an argument to the UserDict() function to create a user dictionary for the given dictionary.
- Store it in another variable.
- Print the above result.
- Create an empty user dictionary using the UserDict() function and store it in another variable.
- Print the above obtained empty user dictionary.
- The Exit of the Program.
Below is the implementation:
# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
# Give the dictionary as static input and store it in a variable.
gvn_dict = {'p': 180, 'q': 190, 'r': 200}
# Pass the given dictionary as an argument to the UserDict() function to
# create a user dictionary for the given dictionary.
# Store it in another variable.
rsltuesr_dicnry = UserDict(gvn_dict)
# Print the above result.
print("The user dictionary for the given dictionary is :")
print(rsltuesr_dicnry.data)
# Create an empty user dictionary using the UserDict() function and store
# it in another variable.
emty_userdictry = UserDict()
# Print the above obtained empty user dictionary.
print("The Empty user dictionary is :")
print(emty_userdictry.data)
Output:
The user dictionary for the given dictionary is :
{'p': 180, 'q': 190, 'r': 200}
The Empty user dictionary is :
{}Example2:
Approach:
- Import UserDict() function from the collections module using the import keyword.
- Create a class by passing the UserDict function as an argument.
- Inside the class, create a function for stopping the deletion of items from a given dictionary.
- Inside the function raise some random RuntimeError.
- Create another function by passing the parameter as none for stopping the poping of items from a given dictionary.
- Inside the function raise some random RuntimeError.
- Create another function by passing the parameter as none for stopping the popitem from a given dictionary.
- Inside the function raise some random RuntimeError.
- Inside the main function,
- Give the dictionary as static input and store it in a variable.
- Create an object for the above class by passing the given dictionary as an argument and store it in another variable.
- Print the given dictionary.
- Delete an item from the dictionary using the pop() function.
- The Exit of the Program.
Below is the implementation:
# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
# Create a class by passing the UserDict function as an argument.
class GivenDictionary(UserDict):
# Inside the class, create a function for stopping
# the deletion of items from a given dictionary.
def delete(self):
# Inside the function raise some random RuntimeError.
raise RuntimeError("You Cannot delete an element from the given dictionary")
# Create another function by passing the parameter as none for stopping the
# poping of items from a given dictionary.
def pop(self, a = None):
# Inside the function raise some random RuntimeError.
raise RuntimeError("You Cannot delete an element from the given dictionary")
# Create another function by passing the parameter as none for stopping the
# popitem from a given dictionary.
def popitem(self, a = None):
# Inside the function raise some random RuntimeError.
raise RuntimeError("You Cannot delete an element from the given dictionary")
# Inside the main function
# Give the dictionary as static input and store it in a variable.
gvn_dict = {'p':4,'q':9 ,'z': 13}
# Create an object for the above class by passing the given dictionary as an argument
# and store it in another variable.
rslt_dictry = GivenDictionary(gvn_dict)
# Print the given dictionary.
print("The given dictionary = ")
print(rslt_dictry)
# Delete an item from the dictionary using the pop() function.
rslt_dictry.pop(1)
Output:
The given dictionary =
{'p': 4, 'q': 9, 'z': 13}
Traceback (most recent call last):
File "jdoodle.py", line 36, in <module>
rslt_dictry.pop(1)
File "jdoodle.py", line 18, in pop
raise RuntimeError("You Cannot delete an element from the given dictionary")
RuntimeError: You Cannot delete an element from the given dictionaryMethod #2: Using collections Module (User Input)
Approach:
- Import UserDict() function from the collections module using the import keyword.
- Take a dictionary and initialize it with an empty dictionary using dict() or {}.
- Give the number of keys as user input using int(input()) and store it in a variable.
- Loop till the given number of keys using for loop.
- Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
- Initialize the key with the value of the dictionary.
- Pass the given dictionary as an argument to the UserDict() function to create a user dictionary for the given dictionary.
- Store it in another variable.
- Print the above result.
- Create an empty user dictionary using the UserDict() function and store it in another variable.
- Print the above obtained empty user dictionary.
- The Exit of the Program.
Below is the implementation:
# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = dict()
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
# Inside the for loop scan the key and value as
# user input using input(),split() functions
# and store them in two separate variables.
keyy, valuee = input(
'Enter key and value separated by spaces = ').split()
# Initialize the key with the value of the dictionary.
gvn_dict[keyy] = valuee
# Pass the given dictionary as an argument to the UserDict() function to
# create a user dictionary for the given dictionary.
# Store it in another variable.
rsltuesr_dicnry = UserDict(gvn_dict)
# Print the above result.
print("The user dictionary for the given dictionary is :")
print(rsltuesr_dicnry.data)
# Create an empty user dictionary using the UserDict() function and store
# it in another variable.
emty_userdictry = UserDict()
# Print the above obtained empty user dictionary.
print("The Empty user dictionary is :")
print(emty_userdictry.data)
Output:
Enter some random number of keys of the dictionary = 3
Enter key and value separated by spaces = x welcome
Enter key and value separated by spaces = y to
Enter key and value separated by spaces = z Python-Programs
The user dictionary for the given dictionary is :
{'x': 'welcome', 'y': 'to', 'z': 'Python-Programs'}
The Empty user dictionary is :
{}Example2:
Approach:
- Import UserDict() function from the collections module using the import keyword.
- Create a class by passing the UserDict function as an argument.
- Inside the class, create a function for stopping the deletion of items from a given dictionary.
- Inside the function raise some random RuntimeError.
- Create another function by passing the parameter as none for stopping the poping of items from a given dictionary.
- Inside the function raise some random RuntimeError.
- Create another function by passing the parameter as none for stopping the popitem from a given dictionary.
- Inside the function raise some random RuntimeError.
- Inside the main function,
- Take a dictionary and initialize it with an empty dictionary using dict() or {}.
- Give the number of keys as user input using int(input()) and store it in a variable.
- Loop till the given number of keys using for loop.
- Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
- Initialize the key with the value of the dictionary.
- Create an object for the above class by passing the given dictionary as an argument and store it in another variable.
- Print the given dictionary.
- Delete an item from the dictionary using the pop() function.
- The Exit of the Program.
Below is the implementation:
# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
# Create a class by passing the UserDict function as an argument.
class GivenDictionary(UserDict):
# Inside the class, create a function for stopping
# the deletion of items from a given dictionary.
def delete(self):
# Inside the function raise some random RuntimeError.
raise RuntimeError("You Cannot delete an element from the given dictionary")
# Create another function by passing the parameter as none for stopping the
# poping of items from a given dictionary.
def pop(self, a = None):
# Inside the function raise some random RuntimeError.
raise RuntimeError("You Cannot delete an element from the given dictionary")
# Create another function by passing the parameter as none for stopping the
# popitem from a given dictionary.
def popitem(self, a = None):
# Inside the function raise some random RuntimeError.
raise RuntimeError("You Cannot delete an element from the given dictionary")
# Inside the main function
# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = dict()
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
# Inside the for loop scan the key and value as
# user input using input(),split() functions
# and store them in two separate variables.
keyy, valuee = input(
'Enter key and value separated by spaces = ').split()
# Initialize the key with the value of the dictionary.
gvn_dict[keyy] = valuee
# Create an object for the above class by passing the given dictionary as an argument
# and store it in another variable.
rslt_dictry = GivenDictionary(gvn_dict)
# Print the given dictionary.
print("The given dictionary = ")
print(rslt_dictry)
# Delete an item from the dictionary using the pop() function.
rslt_dictry.pop(1)
Output:
Enter some random number of keys of the dictionary = 2
Enter key and value separated by spaces = welcometo 12
Enter key and value separated by spaces = Python-Programs 13
The given dictionary =
{'welcometo': '12', 'Python-Programs': '13'}
Traceback (most recent call last):
File "jdoodle.py", line 49, in <module>
rslt_dictry.pop(1)
File "jdoodle.py", line 18, in pop
raise RuntimeError("You Cannot delete an element from the given dictionary")
RuntimeError: You Cannot delete an element from the given dictionary