Python Dictionaries Tutorial with Examples

Python Dictionaries is a collection (or data structure) that is unordered, mutable (changeable) and indexed. In Python, dictionaries are written with curly brackets { }, and they have keys and values. If you have looked at lists and tuples, then Dictionaries is another data type.

Python Dictionaries Tutorial with Examples opreations

Python Dictionaries Syntax and Example 

The dictionary syntax is very simple in python : dict = {"key" : "value",...}

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5, ‘Address’: ‘171 Street 4A, Bangalore, India’}

This is the dictionary example. So here item is referred to as keys, not indexes. For dictionaries you can create custom indexes, so to say and so these are key and value.

Access Single Item in Python Dictionaries

You can access an item in the dictionary by using a key.

Output: Sam

Change the values in Dictionaries :

Let’s Change the address in a python dictionary. It’s very easy with using the key.

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5, ‘Address’: ’14 Street 9C, None’}

Adding new Items :

Just add a new key and it’s value, check this code.

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5, ‘Address’: ‘171 Street 4A, Bangalore, India’, ‘contact’: ‘0987654321’}

Removing Items:

Using del() function in python, you can remove the item from the dictionary. See this example deleting (removed) “Address” item.

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5}

How to Find the Length of the Dictionary?

len() function returns the size (length) of the dictionary:

Output: 4

Do comment if you have any doubts and suggestions.

Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Python Dictionary examples are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.