Latest posts

10/recent/ticker-posts

Dictionaries and the methods of Dictionaries in Python | Creation of Dictionary in Python | Methods of Dictionaries in Python

What is a Dictionary in Python ?

A dictionary is a collection of key-value pairs.
Dictionaries are one of the most commonly used data structures in Python. They allow us to store and manipulate data in key-value pairs, making it easy to retrieve and update information quickly.
Now, we'll explore the basics of dictionaries in Python, including how to create them, add and remove items, and access the data they contain.

Let's see, How to create a Dictionary...

Creation of Dictionaries :

A dictionary is defined using curly brackets '{ }' in python.
To separate each key and value pair we use colons ' : '.

Example : 
my_dict = { 'key1':'value1',
            'key2':'value2',
            'key3':'value3'}

In the given example, we have created a dictionary 'my_dict' with 3 pairs of keys and values.

Realtime example :
person = {'Name':"John",
          'Age':26,
          'City':"Germany"}


So here, we have created another dictionary 'person' with 3 keys 'Name', 'Age', and 'City', and values "John", 26, and "Germany".
Each key refers to its own value. It means Dictionaries are used to store large amounts of accurate data.

Note : As similar to other data structures like set and list, a dictionary is also mutable, but the keys of a dictionary are totally immutable. We cannot change the keys of any dictionary after the declaration, but we can able to change their values.

Adding and Removing Items :

Adding a new element or any pair of keys and values is very simple in the concept of Dictionaries.
Simply assign a new value to a new key,
Suppose there is a dictionary, that contains the details of employee John with some key-value pairs like 'Name', 'Age', and 'City'.
Now we have to add a new pair of 'Salary' in this dictionary, so at that time we are easily able to modify this dictionary.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany"}

# New key-value pair

emp['Salary'] = 45000


Removing Item from Dictionary :

To delete any key-value pair from the dictionary simply use the 'del' keyword.
Give the name of the key to delete it.

Syntax :
del dict_name[key]

Suppose from the recent Example of an employee, we want to delete the 'City' of John, then simply use the 'del' keyword to delete 'City' from the dictionary.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# Deleting 'City'
del emp['City']

print(emp)

# Output :
{'Name': 'John', 'Age': 26, 'Salary': 45000}



Accessing data from the Dictionary :

To access the data from any dictionary, specify the key in square brackets '[ ]'.

Syntax :
dict_name[key]

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# Accesing 'Age'
print("")
print("Age of John is : ",emp['Age'])
print("")


Note : that if you try to access a key that doesn't exist in the dictionary, Python will raise a 'KeyError' exception.

Methods of Dictionaries :

  1. get()
  2. items()
  3. clear()
  4. copy()
  5. keys()
  6. values()
  7. pop()
  8. popitem()
  9. update()

1. get() Method :

Sometimes due to some reasons, we cannot provide proper input in the key section, or after the deletion of any key-value pair we can try to fetch those data, then at that time python shows an error.
To avoid this issue, you can use the get() method to retrieve a value safely. The get() method takes two arguments: the key to retrieve and a default value to return if the key doesn't exist.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# Trying to Fetch City
print("")
print(emp.get("City", "Key-Value pair not Exist"))
print("")



2. items() Method :

Basically, this method is mostly get used with loops, such as for-loop.
This method returns a list of key-value pairs.

Take the reference of our article on for-loop of python to get a better idea of working of for-loop.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# item() Method with for loop

for key, value in emp.items():
    print(key + ": " + str(value))
    
'''
Output :

Name: John
Age: 26      
City: Germany
Salary: 45000

'''



3. clear() Method :

This method is basically used to remove all the keys and values from a dictionary.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

emp.clear()

print(emp)
    
# Output : {}



4. copy() Method :

It returns an exact copy of a given dictionary.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# copy() Method

copy = emp.copy()

print("")
print("Original Dictionary :")
print("")
print(emp)
print("")

print("Copied Dictionary :")
print("")
print(copy)
 
 
'''   
Original Dictionary :

{'Name': 'John', 'Age': 26, 'City': 'Germany', 'Salary': 45000}

Copied Dictionary :

{'Name': 'John', 'Age': 26, 'City': 'Germany', 'Salary': 45000}
'''


5. keys() Method :

It will return the list of keys in the dictionary.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# keys() Method

key = emp.keys()

print("")
print("Original Dictionary :")
print("")
print(emp)
print("")

print("Keys of Dictionary :")
print("")
print(str(key))
 
 
'''   
Original Dictionary :

{'Name': 'John', 'Age': 26, 'City': 'Germany', 'Salary': 45000}

Keys of Dictionary :

dict_keys(['Name', 'Age', 'City', 'Salary'])
'''


6. values() Method :

Similar to the keys() method, this method returns the values of a dictionary.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# values() Method

value = emp.values()

print("")
print("Original Dictionary :")
print("")
print(emp)
print("")

print("Values of Dictionary :")
print("")
print(str(value))
 
 
'''   
Original Dictionary :

{'Name': 'John', 'Age': 26, 'City': 'Germany', 'Salary': 45000}

Values of Dictionary :

dict_values(['John', 26, 'Germany', 45000])
'''


7. pop() Method :

Removes the key-value pair with the given key and returns the corresponding value. If the key does not exist, return the default value (if provided) or raise a 'KeyError'.

Syntax :
dict_name.pop(key, default)

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}

# pop() Method

emp.pop('Age')

error = emp.pop('Country', "Data not found in Dictionary")

print("")
print("Original Dictionary :")
print("")
print(emp)
print("")

print("If item not present :")
print("")
print(str(error))
 
 
'''   
Original Dictionary :

{'Name': 'John', 'City': 'Germany', 'Salary': 45000}

If item not present :

Data not found in Dictionary
'''


8. popitem() Method :

Removes and returns an arbitrary key-value pair from the dictionary. If the dictionary is empty, raises a 'KeyError'.

Example :
emp= {'Name':"John",
          'Age':26,
          'City':"Germany",
          'Salary':45000}


print("")
print("Original Dictionary :")
print("")
print(emp)
print("")

key, value = emp.popitem()

# Dictionary after modification

print("Original Dictionary :")
print("")
print(emp)
print("")
 
'''   
Original Dictionary :

{'Name': 'John', 'Age': 26, 'City': 'Germany', 'Salary': 45000}

Original Dictionary :

{'Name': 'John', 'Age': 26, 'City': 'Germany'}
'''

9. update() Method :

Updates the dictionary with key-value pairs from another dictionary or iterable object. Basically, it will update the values of similar keys from the 2 dictionaries, otherwise adding the pairs of key-value of another dictionary in the main dictionary.

Syntax :
dict_name.update(other_dict)

Example :
emp1= {'Name':"John",
        'Age':26,
        'City':"Germany",
        'Salary':45000}

emp2 = {'Name':"Purvi",
        'Age':21,
        'City':"Pune",
        'Salary':30000,
        'Country':"India"}

print("")
print("Original Dictionary :")
print("")
print(emp1)
print("")

emp1.update(emp2)

# Dictionary after update

print("Updated Dictionary :")
print("")
print(emp1)
print("")
 
'''   
Original Dictionary :

{'Name': 'John', 'Age': 26, 'City': 'Germany', 'Salary': 45000}

Updated Dictionary :

{'Name': 'Purvi', 'Age': 21, 'City': 'Pune', 'Salary': 30000, 'Country': 'India'}
'''



So, that's all about Dictionaries in Python...

Hope it will help you to learn Python Programming more...

Thank you...!!!




Also Visit


Post a Comment

0 Comments