≡ Menu

Python Dictionary Examples – Create, Update and Delete Elements

Dictionary in python consists of keys and their values.

This article is part of our ongoing series on python. In the first article of the series, we explained how to use variables, strings and functions in python.

In this tutorial, we’ll understand the basics of python dictionaries with examples.

1. Create a Python Dictionary

Here is an example of how we can create a dictionary in Python :

>>> myDict = {"A":"Apple", "B":"Boy", "C":"Cat"}

In the above example:

  • A dictionary is created.
  • This dictionary contains three elements.
  • Each element constitutes of a key value pair.
  • This dictionary can be accessed using the variable myDict.

2. Access Dictionary Elements

Once a dictionary is created, you can access it using the variable to which it is assigned during creation. For example, in our case, the variable myDict can be used to access the dictionary elements.

Here is how this can be done :

>>> myDict["A"]
>>> myDict["B"]
>>> myDict["C"]

So you can see that using the variable myDict and Key as index, the value of corresponding key can be accessed. For those who have C/C++ background, its more like accessing the value kept at a particular index in an array.

If you just type the name of the variable myDict, all the key value pairs in the dictionary will be printed.

>>> myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy'}

There is one thing that you need to keep in your mind. Only dictionary keys can be used as indexes. This means that myDict[“A”] would produce ‘Apple’ in output but myDict[“Apple”] cannot produce ‘A’ in the output.

>>> myDict["Apple"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Apple'

So we see that the python compiler complained about ‘Apple’ being used as index.

3. Update Dictionary Elements

Just the way dictionary values are accessed using keys, the values can also be modified using the dictionary keys. Here is an example to modify python dictionary element:

>>> myDict["A"] = "Application"
>>> myDict["A"]
>>> myDict
{'A': 'Application', 'C': 'Cat', 'B': 'Boy'}

You can see that in the example shown above, the value of key ‘A’ was changed from ‘Apple’ to ‘Application’ easily.  This way we can easily conclude that there could not be two keys with same name in a dictionary.

4. Delete Dictionary Elements

Individual elements can be deleted easily from a dictionary. Here is an example to remove an element from dictionary.

>>> myDict
{'A': 'Application', 'C': 'Cat', 'B': 'Boy'}
>>> del myDict["A"]
>>> myDict
{'C': 'Cat', 'B': 'Boy'}

So you can see that by using ‘del’ an element can easily be deleted from the dictionary.

If you want to delete complete dictionary ie all the elements in the dictionary then it can be done using the clear() function. Here is an example :

>>> myDict
{'C': 'Cat', 'B': 'Boy'}
>>> myDict.clear()
>>> myDict

So you see that all the elements were deleted making the dictionary empty.

Characteristics of Python Dictionaries

After discussing all the actions that can be done on dictionaries, lets now understand a couple of important characteristics of dictionaries in Python.

1. Dictionaries are Unordered

Just have a look at the earlier examples that we have used in this article, you will observe that the dictionary elements (key-value pairs) are not in ordered form. Let’s focus on this aspect once again :

>>> myDict = {"A":"Apple", "B":"Boy", "C":"Cat"}
>>> myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy'}

You can observe that the order of elements while the dictionary was being created is different from the order in which they are actually stored and displayed.

Even if you try to add other elements to python dictionary:

>>> myDict["D"] = "Dog"
>>> myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'D': 'Dog'}
>>> myDict["E"] = "Elephant"
>>> myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'E': 'Elephant', 'D': 'Dog'}

You’ll observe that it’s not necessary that elements will be stored in the same order in which they were created.

2. Dictionary Keys are Case Sensitive

Yes, this is true. Same key name but with different case are treated as different keys in python dictionaries.

Here is an example :

>>> myDict["F"] = "Fan"
>>> myDict["f"] = "freeze"
>>> myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'E': 'Elephant', 'D': 'Dog', 'F': 'Fan', 'f': 'freeze'}

In the example above, we tried to create two elements with same key name but different case and you can observe that to separate elements corresponding to same key were created.

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Jon May 9, 2013, 7:07 am

    I love Python dictionaries. I’m working with JSON data from websites (like openweathermap.org and archive.org), which are returned via the json module as dictionaries. Sometimes there are dictionaries within dictionaries, and even more fun are lists of dictionaries, inside the dictionaries.

    Dictionaries are pretty versatile.

  • bob May 9, 2013, 8:23 am

    Good article!!!
    Are there functions available to order the dictionary elements (like say you want to print the values out in some kind of order)

  • Jalal Hajigholamali May 9, 2013, 2:11 pm

    Very useful article
    Thanks a lot

  • Kamal Prasad May 9, 2013, 3:46 pm

    How is dictionary different from hashes in PERL. Also does Python has hashes?

  • RaviTeja May 9, 2013, 11:22 pm

    It is not possible to sort a dict. Dicts are inherently orderless, but other types, such as lists and tuples, are not. They can be sorted.

  • pathum May 10, 2013, 9:34 am

    nice tutorial keep going…..

  • Foxqca March 6, 2015, 10:47 am

    If you want to access elements of a dictionary sorted, try this:

    for k in sorted(dict.keys()):
    element = dict[k]
    #do stuff with element

  • mannat December 30, 2015, 4:54 am

    how can we add,remove and edit elements of a dictionary? We were told dictionaries are immutable.

  • Chanchal Pardeshi June 23, 2016, 8:56 pm

    Good to see an actual simple code that run… you saved my lot of time 🙂 thanku.

  • Anonymous January 2, 2017, 12:55 am

    I’m getting unexpected indent when trying to update dictionary item,
    i have created, animals={key,item}
    updated code:animals[key]=item2

  • Wiley January 17, 2017, 11:26 pm

    This was extremely helpful, thank you!

  • prasad June 21, 2017, 6:58 am

    I want to change the dictionary key names in a loop. Initially the key names are numbers (say: dict={0:’BB’, 1: ‘CC’, 2: ‘DD’). I want to change the keys as
    dict={A:’BB’, B: ‘CC’, C: ‘DD’).
    Here the keys are changed from 0,1,2 to A,B,C.