Learn Python Programming

Python Dictionaries


A dictionary is a collection of a group of elements arranged in the form of key-value pairs. In the dictionary sequence, the first element is considered as ‘key’ and the immediate next to the key is its ‘value’. The key and its value are separated by colon (:). Key value pairs in a dictionary are inserted in curly braces {}.

  • Unordered collection of key-value pair elements
  • Elements are mutable in nature.
  • The values in dictionary items can be of any data type.

Let us understand its syntax with the example.

this_dict = {
    "brand" : "Ford",
    "model" : "Mustang",
    "year"  : 1965
}

print(this_dict)

#Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1965}

Dictionary length

A dictionary length can be find out using the len() function.

this_dict = {
    "brand" : "Ford",
    "model" : "Mustang",
    "year"  : 1965
}

print(len(this_dict))

#Output
3

Accessing elements from Dictionary

In case of dictionary, we can get the specific element of a dictionary using its key. Keys can be used either inside square brackets [] or with the get() method. If we use the square brackets [ ] to access an element from dictionary, a key Error will be raised if that key element not found. To safe from error, we do use get() method which returns none if the key is not found in the dictionary.

my_dict = {'name': 'Deepak', 'age':26}
print(my_dict['name'])
print(my_dict['age'])

#Trying to access a key that does not exist
print(my_dict.get('address'))
print(my_dict['address'])

#Output
Deepak
26
None
Traceback (most recent call last):
  File "strings_character.py", line 7, in <module>
    print(my_dict['address'])
KeyError: 'address'

Changing and adding elements in Dictionary

Python dictionaries are mutable. Dictionary elements can be modified. We can add new items or modify an existing items using the assignment operator (=).

If the key is already available then the value is only updated. In case new key-value (key:value) pair is created and added to dictionary.

#changing and adding elements
my_dict = {'name': 'Deepak', 'age':26}
my_dict['age'] = 28
print(my_dict)

#add new item
my_dict['address'] = 'Noida Film City'
print(my_dict)

#Output
{'name': 'Deepak', 'age': 28}
{'name': 'Deepak', 'age': 28, 'address': 'Noida Film City'}

Removing elements from a dictionary

There are several methods and function which are used to remove elements from dictionary. Let us look one by one.

Pop() method – This method removes an item with the provided key, after removing its returns the removed value.

squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.pop(4))

#Output
16

Popitem() method – This method is used to remove and returns an arbitrary key-value item pair from dictionary.

squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.popitem())

#Output
(5, 25)

clear() method – This method is used to remove all item from a dictionary.

squares = {1:1, 2:4, 3:9, 4:16, 5:25}
squares.clear()
print(squares)

#Output
{}

del keyword – This is used to delete the entire dictionary itself.

squares = {1:1, 2:4, 3:9, 4:16, 5:25}
del squares
print(squares)

#Output
Traceback (most recent call last):
  File "strings_character.py", line 3, in <module>
    print(squares)
NameError: name 'squares' is not defined

Other Important Dictionary methods/functions

  • clear()
  • copy()
  • fromkeys(sql[,v])
  • get(keyId)
  • items()
  • keys()
  • pop(keyId)
  • popitem()
  • setdefault()
  • update([other])
  • values()

Dictionary built in functions

  • all()
  • any()
  • len()
  • cmp() (not available in python 3)
  • sorted()