Python Tutorial (14) - Dictionary

Time: Column:Python views:298

Dictionaries in Python

A dictionary is another mutable container model that can store any type of object.

Each key-value pair in a dictionary is written as key => value and separated by a colon (:). Pairs are separated by commas (,), and the entire dictionary is enclosed within curly braces {}, as shown in the format below:

d = {key1: value1, key2: value2, key3: value3}

Note: Since dict is a Python keyword and built-in function, it's best to avoid naming your variables dict.

Python Tutorial (14) - Dictionary

  • Keys must be unique, but values do not need to be.

  • Values can be of any data type, but keys must be immutable, such as strings or numbers.

Example of a Simple Dictionary:

tinydict = {'name': 'runoob', 'likes': 123, 'url': 'www.runoob.com'}

Python Tutorial (14) - Dictionary

Alternative Dictionary Creation:

tinydict1 = {'abc': 456}
tinydict2 = {'abc': 123, 98.6: 37}

Creating an Empty Dictionary

You can create an empty dictionary using curly braces {}.

Example:

# Creating an empty dictionary using {}
emptyDict = {}

# Printing the dictionary
print(emptyDict)

# Checking the number of items in the dictionary
print("Length:", len(emptyDict))

# Checking the type of the dictionary
print(type(emptyDict))

Output:

{}
Length: 0
<class 'dict'>


You can also create an empty dictionary using the built-in dict() function.

Example:

emptyDict = dict()

# Printing the dictionary
print(emptyDict)

# Checking the number of items in the dictionary
print("Length:", len(emptyDict))

# Checking the type of the dictionary
print(type(emptyDict))

Output:

{}
Length: 0
<class 'dict'>


Accessing Values in a Dictionary

You can access dictionary values by placing the corresponding key within square brackets, as shown in the example below:

Example:

#!/usr/bin/python3

tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

print("tinydict['Name']: ", tinydict['Name'])
print("tinydict['Age']: ", tinydict['Age'])

Output:

tinydict['Name']:  Runoob
tinydict['Age']:  7


If you attempt to access a key that doesn't exist in the dictionary, Python will raise a KeyError.

Example:

#!/usr/bin/python3

tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

print("tinydict['Alice']: ", tinydict['Alice'])

Output:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print("tinydict['Alice']: ", tinydict['Alice'])
KeyError: 'Alice'


Modifying a Dictionary

To add new content to a dictionary, you can add new key-value pairs, or modify or delete existing ones. See the example below:

Example:

#!/usr/bin/python3

tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

tinydict['Age'] = 8                # Update Age
tinydict['School'] = "Course"    # Add new key-value pair

print("tinydict['Age']: ", tinydict['Age'])
print("tinydict['School']: ", tinydict['School'])

Output:

tinydict['Age']:  8
tinydict['School']:  Course


Deleting Dictionary Elements

You can delete individual elements or clear the entire dictionary with a single operation.

To explicitly delete an element from the dictionary, you can use the del command as shown below:

Example:

#!/usr/bin/python3

tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

del tinydict['Name']  # Delete key 'Name'
tinydict.clear()      # Clear the dictionary
del tinydict          # Delete the dictionary

print("tinydict['Age']: ", tinydict['Age'])
print("tinydict['School']: ", tinydict['School'])

This will raise an exception because the dictionary no longer exists after the del operation:

Output:

Traceback (most recent call last):
  File "/runoob-test/test.py", line 9, in <module>
    print("tinydict['Age']: ", tinydict['Age'])
NameError: name 'tinydict' is not defined


Note: We will discuss the del() method later.

Dictionary Key Characteristics

The values of a dictionary can be any Python object, either standard or user-defined. However, the keys have some restrictions.

There are two important points to remember:

  1. Duplicate keys are not allowed: If a dictionary is created with duplicate keys, only the last occurrence of the key will be remembered. See the example below:

Example:

#!/usr/bin/python3

tinydict = {'Name': 'Runoob', 'Age': 7, 'Name': 'Course'}

print("tinydict['Name']: ", tinydict['Name'])

Output:

tinydict['Name']:  Course


  1. Keys must be immutable: This means that numbers, strings, or tuples can be used as dictionary keys, but not lists. See the example below:

Example:

#!/usr/bin/python3

tinydict = {['Name']: 'Runoob', 'Age': 7}

print("tinydict['Name']: ", tinydict['Name'])

This will raise an exception because lists are mutable and cannot be used as dictionary keys:

Output:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    tinydict = {['Name']: 'Runoob', 'Age': 7}
TypeError: unhashable type: 'list'

Built-in Functions and Methods of Dictionaries

Python dictionaries include the following built-in functions:

IndexFunction & DescriptionExample
1len(dict)Calculates the total number of elements in the dictionary, i.e., the total number of keys.


python<br>tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}<br>len(tinydict)<br># Output: 3
2str(dict)Outputs the dictionary as a printable string representation.


python<br>tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}<br>str(tinydict)<br># Output: "{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
3type(variable)Returns the type of the input variable; if the variable is a dictionary, it returns the dictionary type.


python<br>tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}<br>type(tinydict)<br># Output: <class 'dict'>

Built-in Methods of Python Dictionaries

IndexMethod & Description
1dict.clear()
2dict.copy()
3dict.fromkeys(seq, val)
4dict.get(key, default=None)
5key in dict
6dict.items()
7dict.keys()
8dict.setdefault(key, default=None)
9dict.update(dict2)
10dict.values()
11dict.pop(key, [default])
12dict.popitem()