python logo


Tag: dictionairy

python dictionary

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:
Python Programming Bootcamp: Go from zero to hero

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'}

If you are new to Python programming, I highly recommend this book.

Download Python Exercises