Dictionary in Python

A dictionary is a datatype in Python which holds an unordered, mutable collection of elements. These elements are present in the form of key-value pairs. The dictionary maps each key to individual value.

A dictionary is capable of holding any number of key-value pairs. Each key present in the dictionary must be unique, and they are immutable(unchangeable), while repetition in values is allowed and multiple datatypes can be stored in the dictionary.

This article will tell you about:

  1. How to create a dictionary?
  2. dict() function
  3. How to access the dictionary elements?
  4. How to insert/change the dictionary elements?
  5. How to delete the dictionary elements?
  6. For loop with Python Dictionary.
  7. Dictionary Methods

How to create a dictionary in Python?

Syntax:
dictionary_name = { key1:value1 , key2:value2 , key3:value3 ... }

  • A dictionary is created with curly braces { }.
  • A comma is used in a dictionary to separate different key-value pairs.
  • A colon is inserted between the key and its respective value. The key is towards the right of the colon whereas value is towards the right.

Python Built-in function dict()

To create a dictionary, you can also use a function dict().

Syntax:
dictionary_name = dict({ key1:value1, key2:value2, key3:value3 ... })

Example:

Emp_details = { 'Name':'Gaurav Raj', 'Age':35, 'Profile':'PHP Developer'}
print('Emp_details =', Emp_details)

#using dict() function to create a dictionary.
Books = ({ 'Novels':45, 'Story Books':92, 'Science':56, 'Mathematics':60})
print('Books =', Books)

Output:

Emp_details = {'Name': 'Gaurav Raj', 'Age': 35, 'Profile': 'PHP Developer'}

Books = {'Novels': 45, 'Story Books': 92, 'Science': 56, 'Mathematics': 60}

How to access the dictionary elements in Python?

There are two methods to access the dictionary elements.

1. Square brackets: To retrieve a particular value from the dictionary, you must know the respective key to it. The dictionary name is followed by the key which is placed within the square brackets.

Syntax:
dictionary_name[key]

2. get() function: Python also provides a function get() to access the value present in the dictionary. The key of the required value is passed as the argument to this function.

Syntax:
dictionary_name.get(key)

Example:

Emp_details = { 'Name':'Gaurav Raj', 'Age':35, 'Profile':'PHP Developer'}
print('Emp_details =', Emp_details)

#using square brackets to access the value.
print(Emp_details['Name'])

#using get() function to access the value.
print(Emp_details.get('Age'))

Output:

Emp_details = {'Name': 'Gaurav Raj', 'Age': 35, 'Profile': 'PHP Developer'}
Gaurav Raj
35

The two methods given above perform the same task, but they behave differently in one situation. In case, the key given by the user is not present in the dictionary:

  • The first method, i.e. accessing with the help of square brackets, generates an error called keyerror.
    Let us try to access a key 'Contact' which does not exist in the dictionary created in the previous program.

Example:

Emp_details = { 'Name':'Gaurav Raj', 'Age':35, 'Profile':'PHP Developer'}
print('Emp_details =', Emp_details)

#using square brackets to access the value.
print(Emp_details['Contact'])

Output:

Emp_details = {'Name': 'Gaurav Raj', 'Age': 35, 'Profile': 'PHP Developer'}

Traceback (most recent call last):
File "C:/Users/TS7/AppData/Local/Programs/Python/Python37/dictionary.py", line 5, in <module>
print(Emp_details['Contact'])
KeyError: 'Contact'
  • The get() function return an output 'None'.

Example:

Emp_details = { 'Name':'Gaurav Raj', 'Age':35, 'Profile':'PHP Developer'}
print('Emp_details =', Emp_details)

#using get() function to access the value.
print(Emp_details.get('Contact'))

Output:

Emp_details = {'Name': 'Gaurav Raj', 'Age': 35, 'Profile': 'PHP Developer'}

None

How to insert/change the dictionary elements in Python?

Syntax:
dictionary[key] = value

  • Inserting the new element:
    You can insert a new element in the dictionary by providing a new key inside the square brackets. With the help of assignment operator (=), a value is given to this new key.
  • Changing the existing element:
    To change a specific value in the dictionary, you need to enter the respective key in the square brackets. The assigment operator will change the value of the key.

Example:

Emp_details = { 'Name':'Gaurav Raj', 'Age':35, 'Profile':'PHP Developer'}
print('Emp_details =', Emp_details)

#inserting a new element.
Emp_details['Contact'] = 32456232
print('After insertion :-\nEmp_details = ', Emp_details)

#changing an existing element.
Emp_details['Name'] = 'Divya Bansal'
print('After changing the value :-\nEmp_details =', Emp_details)

Output:

Emp_details = {'Name': 'Gaurav Raj', 'Age': 35, 'Profile': 'PHP Developer'}

After insertion :-
Emp_details = {'Name': 'Gaurav Raj', 'Age': 35, 'Profile': 'PHP Developer', 'Contact': 32456232}

After changing the value :-
Emp_details = {'Name': 'Divya Bansal', 'Age': 35, 'Profile': 'PHP Developer', 'Contact': 32456232}

How to delete an element from Python dictionary?

  • pop() function: deletes one element at a time.
    This built-in function deletes the specified element from the dictionary. The Key of the element which is to be removed is passed as an argument to this function.
    Along with deletion, this function returns the deleted value.

    Syntax
    :
    dictionary_name.pop(key)

  • popitem() function: deletes an arbitrary element.
    This function removes an arbitrary element from the dictionary. This function doesn't require any argument. The deleted element i.e the key-value pair is returned by the function.

    Syntax:
    dictionary_name.popitem()

  • clear() function: removes all the elements of the dictionary.
    You can use this function when you want to empty a dictionary. It deletes all the elements in one go.

    Syntax:
    dictionary_name.clear()

  • del keyword: deletes a single item or the whole dictionary.

    Syntax:
    del dictionary_name[key]

    This statement will delete the element with the given key.

    Syntax:
    del dictionary_name

    This statement will delete the whole dictionary.

Example:

data = { 'a':67, 'b':90, 'c':34, 'd':49, 'e':10, 'f':23 }
print('data =', data)

#using pop() function
x = data.pop('c') #assigning the return value of the function to the variable x.
print('data =', data)
print('Deleted value =', x)

#using popitem() function
y = data.popitem() #assigning the return value of the function to the variable y.
print('data =', data)
print('Deleted element =', y)

#using del keyword to delete one element
del data['d']
print('data =', data)

#using clear() function
data.clear()
print('data =', data)

#using del keyword to delete the whole dictionary
del data
print('data =', data)

Output:

data = {'a': 67, 'b': 90, 'c': 34, 'd': 49, 'e': 10, 'f': 23}

data = {'a': 67, 'b': 90, 'd': 49, 'e': 10, 'f': 23}
Deleted value = 34

data = {'a': 67, 'b': 90, 'd': 49, 'e': 10}
Deleted element = ('f', 23)

data = {'a': 67, 'b': 90, 'e': 10}

data = {}

Traceback (most recent call last):
File "C:/Users/TS7/AppData/Local/Programs/Python/Python37/dictionary.py", line 24, in <module>
print('data =', data)
NameError: name 'data' is not defined.

For loop with Python Dictionary

You can use the for loop with dictionary to access each element one by one.

Example:

data = { 'a':67, 'b':90, 'c':34, 'd':49, 'e':10, 'f':23 }
print('data =', data)

for y in data:
   print(data[y])

Output:

data = {'a': 67, 'b': 90, 'c': 34, 'd': 49, 'e': 10, 'f': 23}
67
90
34
49
10
23

Dictionary Methods in Python

Python provides some methods to work with dictionaries.

  • keys()
    This method returns a list of all the keys present in the dictionary.

    Example:
    data = { 'a':67, 'b':90, 'c':34, 'd':49, 'e':10, 'f':23 }
    print('data =', data)
    print(data.keys())​
    Output:
    data = {'a': 67, 'b': 90, 'c': 34, 'd': 49, 'e': 10, 'f': 23}
    dict_keys(['a', 'b', 'c', 'd', 'e', 'f'])​
  • values()
    This method gives a list of all the values.

    Example:
    data = { 'a':67, 'b':90, 'c':34, 'd':49, 'e':10, 'f':23 }
    print('data =', data)
    print(data.values())​
    Output:
    data = {'a': 67, 'b': 90, 'c': 34, 'd': 49, 'e': 10, 'f': 23}
    dict_values([67, 90, 34, 49, 10, 23])​
  • items()
    This method returns a list of tuples. Each tuple contains one key-value pair.

    Example:
    data = { 'a':67, 'b':90, 'c':34, 'd':49, 'e':10, 'f':23 }
    print('data =', data)
    print(data.items())​
    Output:
    data = {'a': 67, 'b': 90, 'c': 34, 'd': 49, 'e': 10, 'f': 23}
    
    dict_items([('a', 67), ('b', 90), ('c', 34), ('d', 49), ('e', 10), ('f', 23)])​
  • copy()
    This method returns a duplicate copy of the dictionary.

    Example:
    data = { 'a':67, 'b':90, 'c':34, 'd':49, 'e':10, 'f':23 }
    print('data =', data)
    print('Duplicate copy =', data.copy())​
    Output:
    data = {'a': 67, 'b': 90, 'c': 34, 'd': 49, 'e': 10, 'f': 23}
    
    Duplicate copy = {'a': 67, 'b': 90, 'c': 34, 'd': 49, 'e': 10, 'f': 23}​