Python dictionaries


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 Courses:

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

Back
Next

15 thoughts on “Python dictionaries

  1. Frank
    Jam - July 14, 2016

    hi,
    I am a new learner of Python, and confused of single quotation(‘ ‘) and double quotation(” “) marks.
    here is an example:

    words = {}
    words["Hello"] = "Bonjour"
    words["Yes"] = "Oui"
    words["No"] = "Non"
    words["Bye"] = "Au Revoir"
     
    print words            # print key-pairs.
    Output:
    {'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}

    So, why the output is not {Yes: Oui, Bye: Au Revoir, Hello: Bonjour, No: Non} ?
    And what’s the difference between this two definitions, does( ” ” ) means TWO( ‘ ‘ ) ?

    words["Hello"] = "Bonjour"  #double quotation 
    words['Hello'] = "Bonjour"     #single quotation

    Thanks.

    1. Frank
      Frank - July 15, 2016

      There is no specific difference between single and double quotation in the Python language, it’s just a matter of preference. Python supports single, double and triple quotes. Output is always single quotes

Leave a Reply