Dictionary in Python

Keywords: dictionary, array, list, immutable

List python programming

Dictionary in python is a collection of elements that don’t have a specific order, but are indexed with a key. The elements of a dictionary can be changed.

What is a dictionary in Python?

A dictionary works like an encyclopedia. With a given key, you get back the value that the key belongs to. You can view it as a telephone list, where each person (key) has a telephone number (value) associated to them.

 Dictionary works like an encyclopedia

In other words, there is a key connected to the every element in the dictionary. For example, like a bank that has a key for every deposit box.

How to create a dictionary in Python?

When creating a dictionary

  • First assign a name followed by a equal sign =
  • Then elements within curly brackets { } – Each element has a key, and a value
  • The key has data type string, followed by a semicolon (:), followed by the value and ending with a comma

Syntax: Dictionary in Python

If we use the instructions above and enter it in our code-editor

dictionaryName = {

    "Key 1" : value 1,
    "Key 2" : value 2,
    "Key 3" : value 3,
     so on.. 

Example: Create a dictionary in Python

Let’s take a quite simple example on how to create a Dictionary. Say we want to create a dictionary for a dog.

dog_dictionary {

    "Name" : "Mary", 
    "Age" : 3, 
    "Breed of dog" : "Golden Retriever" 



The result then becomes

{'Name': 'Mary', 'Age': 3, 'Breed of dog': 'Golden Retriever'}

Furthermore, you can then always invoke a value, using the associated key:


We will get


Change the value in a Dictionary

Let’s use the same dictionary that we created for our dog.

dog_dictionary { 

     "Name" : "Mary", 
     "Age" : 3, 
     "Breed of dog" : "Golden Retriever" 

But we have realized that we put the wrong value in one of the elements, this is easily fixed. We have noted that our dog Mary is of the breed German Shepherd instead, we can simply write:

dog_dictionary["Breed of dog"] = "German Shepherd"

We simply use the key for that element and then put the new value that we want connected to that key.

Let’s print the correct value for our dog that we named Mary


Results in:

{'Name': 'Mary', 'Age': 3, 'Breed of dog': 'German Shepherd'}

For more information about Dictionaries in Python we recommend the Python Docs website