Easy Tutorial
❮ Python Smtp Python Ascii Character ❯

Python3 Dictionary

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

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

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

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

Keys must be unique, but values do not have to be.

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

A simple dictionary example:

tinydict = {'name': 'tutorialpro', 'likes': 123, 'url': 'www.tutorialpro.org'}

Dictionaries can also be created like this:

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

Creating an Empty Dictionary

Use curly braces { } to create an empty dictionary:

Example

# Using curly braces {} to create an empty dictionary
emptyDict = {}

# Print the dictionary
print(emptyDict)

# Check the length of 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:

Example

emptyDict = dict()

# Print the dictionary
print(emptyDict)

# Check the length of the dictionary
print("Length:", len(emptyDict))

# Check the type
print(type(emptyDict))

Output of the above example:

{}
Length: 0
<class 'dict'>

Accessing Values in a Dictionary

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

Example

#!/usr/bin/python3

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

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

Output of the above example:

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

If you use a key that does not exist in the dictionary, an error will be output as follows:

Example

#!/usr/bin/python3

tinydict = {'Name': 'tutorialpro', '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'

Modifying a Dictionary

To add new content to a dictionary, add new key/value pairs, or modify or delete existing key/value pairs, as shown in the example below:

Example

#!/usr/bin/python3

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

tinydict['Age'] = 8               # Update Age
tinydict['School'] = "tutorialpro.org"  # Add information

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

Output of the above example:

tinydict['Age']:  8
tinydict['School']:  tutorialpro.org

Deleting Dictionary Elements

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

To explicitly delete a dictionary, use the del command, as shown in the example below:

Example

#!/usr/bin/python3

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

del tinydict['Name'] # Delete the 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:

Traceback (most recent call last):
  File "/tutorialpro-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.

Characteristics of Dictionary Keys

Dictionary values can be any Python object, both standard and user-defined, but keys cannot.

Two important points to remember:

1) Duplicate keys are not allowed. If the same key is assigned more than once, the last value will be remembered, as shown in the following example:

#!/usr/bin/python3

tinydict = {'Name': 'tutorialpro', 'Age': 7, 'Name': 'guru'}

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

Output of the above example:

tinydict['Name']:  guru

2) Keys must be immutable, so numbers, strings, or tuples can be used, but lists cannot, as shown in the following example:

#!/usr/bin/python3

tinydict = {['Name']: 'tutorialpro', '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']: 'tutorialpro', 'Age': 7}
TypeError: unhashable type: 'list'

Built-in Functions & Methods for Dictionaries

Python dictionaries include the following built-in functions:

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

Python dictionaries include the following built-in methods:

No. Function & Description
1 dict.clear() <br>Removes all elements from the dictionary
2 dict.copy() <br>Returns a shallow copy of the dictionary
3 dict.fromkeys() <br>Creates a new dictionary with keys from a sequence and values set to a specified value
4 dict.get(key, default=None) <br>Returns the value for the specified key, or a default value if the key is not in the dictionary
5 key in dict <br>Returns true if the key is in the dictionary dict, otherwise returns false
6 dict.items() <br>Returns a list-like view of the dictionary's key-value pairs
7 dict.keys() <br>Returns a view object of the dictionary's keys
8 dict.setdefault(key, default=None) <br>Similar to get(), but will add the key to the dictionary with a value of default if the key does not exist
9 dict.update(dict2) <br>Updates the dictionary with the key-value pairs from dict2
10 dict.values() <br>Returns a view object of the dictionary's values
11 pop(key[,default]) <br>Removes and returns the value for the specified key in the dictionary
12 popitem() <br>Removes and returns the last key-value pair from the dictionary
❮ Python Smtp Python Ascii Character ❯