Reading about Python? Actually practice it. Try PyChallenge free

Python Tutorial

Python dictionaries

Python hosting: PythonAnywhere — host, run and code Python in the cloud. Free tier available.

A dictionary can be thought of as an unordered set of key: value pairs.

A pair of braces creates an empty dictionary: {}.  Each element can maps to a certain value.  An integer or string can be used for the index. Dictonaries do not have an order.

Related Course:
Practice Python with interactive exercises

Dictionary example

Let us make a simple dictionary:

#!/usr/bin/python

words = {} words["Hello"] = "Bonjour" words["Yes"] = "Oui" words["No"] = "Non" words["Bye"] = "Au Revoir"

print(words["Hello"]) print(words["No"])

Output:

Bonjour
Non

We are by no means limited to single word defintions in the value part. A demonstration:

#!/usr/bin/python

dict = {} dict['Ford'] = "Car" dict['Python'] = "The Python Programming Language" dict[2] = "This sentence is stored here."

print(dict['Ford']) print(dict['Python']) print(dict[2])

Output:

Car
The Python Programming Language
This sentence is stored here.

Manipulating the dictionary

We can manipulate the data stored in a dictionairy after declaration.  This is shown in the example below:
#!/usr/bin/python

words = {} words["Hello"] = "Bonjour" words["Yes"] = "Oui" words["No"] = "Non" words["Bye"] = "Au Revoir"

print(words) # print key-pairs. del words["Yes"] # delete a key-pair. print(words) # print key-pairs. words["Yes"] = "Oui!" # add new key-pair. print(words) # print key-pairs.

Output:

{'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Yes': 'Oui!', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
BackNext
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.
Practice Python with interactive exercises