Skip to content

Python3 Dictionaries

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

Each key-value key=>value pair in a dictionary is separated by a colon : and each pair is separated by a comma (,). The entire dictionary is enclosed in curly braces {}. The format is as follows:

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

Note: Since dict is a Python keyword and built-in function, it is not recommended to name a variable dict.

Keys must be unique, but values do not.

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

A simple dictionary example:

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

You can also create dictionaries like this:

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

Use curly braces { } to create an empty dictionary:

# Use curly braces {} to create an empty dictionary
emptyDict = {}
 
# Print the dictionary
print(emptyDict)
 
# Check the number of items in the dictionary
print("Length:", len(emptyDict))
 
# Check the type
print(type(emptyDict))

Output of the above example:

{}
Length: 0
<class 'dict'>

Use the built-in function dict() to create a dictionary:

emptyDict = dict()
 
# Print the dictionary
print(emptyDict)
 
# Check the number of items in the dictionary
print("Length:",len(emptyDict))
 
# Check the type
print(type(emptyDict))

Output of the above example:

{}
Length: 0
<class 'dict'>

Put the corresponding key in square brackets, as shown in the example below:

#!/usr/bin/python3
 
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
print ("tinydict['Name']: ", tinydict['Name'])
print ("tinydict['Age']: ", tinydict['Age'])

Output of the above example:

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

If you access data using a key that does not exist in the dictionary, an error will be thrown as follows:

#!/usr/bin/python3
 
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
print ("tinydict['Alice']: ", tinydict['Alice'])

Output of the above example:

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

The way to add new content to a dictionary is to add new key/value pairs. Modifying or deleting existing key/value pairs is shown in the example below:

#!/usr/bin/python3
 
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
tinydict['Age'] = 8               # Update Age
tinydict['School'] = "Runoob Tutorial"  # Add new entry
 
 
print ("tinydict['Age']: ", tinydict['Age'])
print ("tinydict['School']: ", tinydict['School'])

Output of the above example:

tinydict['Age']:  8
tinydict['School']:  Runoob Tutorial

You can delete individual elements or clear the entire dictionary. Clearing requires only a single operation.

Explicitly delete a dictionary using the del command, as shown in the example below:

#!/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'])

But this will raise an exception because the dictionary no longer exists after executing the del operation:

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: The del() method will also be discussed later.

Dictionary values can be any Python object, whether standard objects or user-defined ones, but keys cannot.

Two important points to remember:

  1. The same key cannot appear twice. If the same key is assigned twice during creation, the later value will be remembered, as shown in the example below:
#!/usr/bin/python3
 
tinydict = {'Name': 'Runoob', 'Age': 7, 'Name': 'Little Rookie'}
 
print ("tinydict['Name']: ", tinydict['Name'])

Output of the above example:

tinydict['Name']:  Little Rookie
  1. Keys must be immutable, so you can use numbers, strings, or tuples, but not lists, as shown in the example below:
#!/usr/bin/python3
 
tinydict = {['Name']: 'Runoob', 'Age': 7}
 
print ("tinydict['Name']: ", tinydict['Name'])

Output of the above example:

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

Python dictionaries include the following built-in functions:

No. Function & Description Example
1 len(dict)
Counts the number of dictionary elements, i.e., the total number of keys.
>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> len(tinydict)
3
2 str(dict)
Outputs the dictionary as a printable string representation.
>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> str(tinydict)
"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
3 type(variable)
Returns the type of the input variable. If the variable is a dictionary, it returns the dictionary type.
>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> type(tinydict)
<class 'dict'>

Python dictionaries include the following built-in methods:

No. Function & Description
1 dict.clear()
Deletes all elements in the dictionary
2 dict.copy()
Returns a shallow copy of the dictionary
3 dict.fromkeys()
Creates a new dictionary using elements from seq as keys and val as the initial value for all keys
4 dict.get(key, default=None)
Returns the value of the specified key. If the key is not in the dictionary, returns the default value
5 key in dict
Returns true if the key is in the dictionary, otherwise false
6 dict.items()
Returns a view object as a list
7 dict.keys()
Returns a view object
8 dict.setdefault(key, default=None)
Similar to get(), but if the key does not exist in the dictionary, it adds the key and sets the value to default
9 dict.update(dict2)
Updates the key/value pairs from dict2 into dict
10 dict.values()
Returns a view object
11 dict.pop(key[,default])
Deletes the value corresponding to the dictionary key and returns the deleted value.
12 dict.popitem()
Returns and deletes the last key-value pair in the dictionary.

Exercises