Dictionary Methods in Python with Examples

Dictionary Methods in Python: We can perform various operations on the dictionary using inbuilt dictionary methods in python. There are different types of dictionary methods available in python. Dictionary stores keys and values. Keys are always unique but values may be the same or different.

dictionary methods in python

Dictionary operations in Python:

1). Accessing elements of DictionaryWe can access elements of a dictionary by using the key names of the dictionary. We use square[] brackets for that. The syntax is quite similar to List. But in a dictionary, we use key for accessing an element of the dictionary.

# Method-1
# Accessing Dictionary Elements

test = {'key1':'value1','key2':'value2'}
x = test["key1"]
print(x)

# output
value1

# Method-2
# Accessing Dictionary Elements

y = test.get("key2")
print(y)

# output
value2

2). Updating Values in DictionaryWe can also update the values of a dictionary as it is mutable.

Example 1:

#Changing Values of Dictionary

test = {
  "brand": "Ferrary",
  "model": "Mcdez",
  "year": 1967
}
test["year"] = 2020
print(test)

# output
#{"brand": "Ferrary","model": "Mcdez","year": 2020}

3). Remove or Delete Operation on Dictionary: There are several ways to remove or delete items/elements from a dictionary. We can also remove elements from a dictionary by using del keyword.

NoteIn a dictionary, there’s always exists keys and values together so if we delete any key from a dictionary then the values which are referring to that particular key will also be deleted automatically. Hence removal of key also affects the values referring to that key.

del also used to delete dictionary completely. [ syntax:  del dictionary_name ]

Example 1: Using del

#Delete operation in Dictionary

test = {'key1':'value1','key2':'value2'}
del test["key1"]
print(test)

# output
# {'key2':'value2'}

Example 2: Using pop()

Pop() method: We have learnt about the del keyword above, del keyword is used to delete key & values referring to each other. Let’s say if we want to delete the value of key1 then we use del(‘key1’). Hence value and key associated with each other will be deleted. In the dictionary pop() method is also used to delete key and values associated with each other.

Example 1:

#Pop() method in Dictionary

test = {
  "name": "Ferrari",
  "model_name": "Mc-dez",
  "year_manufacture": 1980
}
test.pop("name")
print(test)

# output
# {"model_name":"Mc-dez","year_manufacture":1980}

Example 3: </strong class=”cvar”>Using popitem()

popitem() method: The popitem()method is used to remove the last inserted item in the dictionary( in versions before 3.7, a random item is removed instead)

# popitem() in dictionary

test = {
  "name": "Ferrari",
  "model_name": "Mc-dez",
  "year_manufacture": 1980
}
test.popitem()
print(test)

# output
# {"brand_name": "Ferrari", "model_name": "Mc-dez"}

4). Length Function in DictionaryWe have already used this function in our previous topic which is ListThe syntax of getting the length of a dictionary is also similar. Refer to the below given example:

#Lenght() in Dictionary

test = {'key1':'value1','key2':'value2'}
z = len(test)
print(z)

# output
#2

5). Membership and if operator in DictionaryWe have already discussed membership operator in our previous Python Operators topic. Here we are going to learn about new conditional statements if. For now, just take if conditional statement as a reference. In short, it is used to check True or False condition. If condition is True then the statement inside if executes else not. Read this article (if conditional statements.) to learn about if conditional statement in detail.

Example 1: 

#Membership and if operator in Dictionary

test = {
  "name": "Ferrari",
  "model_name": "Mc-dez",
  "year_manufacture": 1980
}
if "name" in test:
  print("Yess!, 'name' is the key available in test dictionary")

# output
# "Yess!, 'name' is the key available in test dictionary"

6). Adding Elements to DictionaryWe can also add elements to our dictionary. While adding elements to our dictionary we should always remember that key name should always be unique otherwise it will replace the value of previous keys.

Example:

#Adding Elements to Dictionary

test = {
  "name": "Ferrari",
  "model_name": "Mc-dez"
}
test["year_manufacture"] = 1980
print(test)

# output
# {"name": "Ferrari","model_name": "Mc-dez","year_manufacture": 2020}

7). Clear() MethodClear() method is used to empty dictionary completely.

Example

# Clear() method in Dictionary

test = {
  "name": "Ferrari",
  "model_name": "Mc-dez",
  "year_manufacture": 1980
}
test.clear()
print(test)

# output
# {}

8). Aliasing and CopyingWe already know that dictionaries are mutable, so we need to be aware of aliasing. As we already discussed that whenever two variables are referring to the same object, in that case, if we do any change in one results then it will reflect in the other also.

dictionary in python

Here if we perform operation 1 then it is the same as equal to 2.

NoteWe cannot copy a dictionary simply by just typing a = b, in this case, b is only a reference to a and changes made to b results in a change to a also.

If we want to modify a dictionary and wants to keep a copy of the original one. We use copy() method.

Example

#Copying Dictionary

test = {
  "name": "Ferrari",
  "model_name": "Mc-dez",
  "year_manufacture": 2020
}
dict = test.copy()
print(dict)

# output
# {"name":"Ferrari","model_name":"Mc-dez","year_manufacture":2020}

9). Nested DictionariesDictionaries inside other dictionary or we can say that more than one dictionary lying in the one dictionary is called Nested Dictionary.

nested dictionary in python

Example

#Nested Dictionary Example

records = {
  "Parent1" : {
    "name" : "Rozy",
    "DOB" : 1998
  },
  "Parent2" : {
    "name" : "Lita",
    "DOB" : 2002
  },
  "Parent3" : {
    "name" : "Clutos",
    "DOB" : 2004
  }
}

print(records)

Output:

# {'Parent1': {'name': 'Rozy', 'DOB': 1998}, 
#  'Parent2': {'name': 'Lita', 'DOB': 2002}, 
#  'Parent3': {'name': 'Clark', 'DOB': 2004}}

10). dict() constructorWe can use dict() constructor to make dictionary explicitly. This is the alternative method to create a dictionary.

Example

#dict() constructor or method

test = dict(name="Ferrari", 
model_name="Mc-dez", year_manufacture=2020)
print(test)

# output
# {'model_name': 'Mc-dez', 'year_manufacture': 2020, 'name': 'Ferrari'}

Note:

  • Keywords should not be string literals.
  • Point out the use of equals instead of a colon for the assignment.

Summary of Dictionary Methods

[table id=13 /]

Glossary

  • key-value pair: One of the item in a dictionary.
  • Dictionary: A collection of keys and values. These are mutable and can be accessed using indexes.
  • key: A unique term that is associated with the value of a dictionary.
  • Method: We can also say it a kind of function.
  • Invoke: It is the term used to call a function.