Home » Python » Python Dictionary with Examples

About Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.

Python Dictionary with Examples

1. Introduction

This is an article about dictionaries in python. A dictionary is a collection of unique key and value pairs. It is used to save data with a key and a value. The key-value pairs are stored in the dictionary.

2. Dictionary – Python

2.1 Prerequisites

Python 3.6.8 is required on windows or any operating system. Pycharm is needed for python programming.

2.2 Download

Python 3.6.8 can be downloaded from the website. Pycharm is available at this link.

2.3 Setup

2.3.1 Python Setup

To install python, the download package or executable needs to be executed.

2.4 IDE

2.4.1 Pycharm Setup

Pycharm package or installable needs to be executed to install Pycharm.

2.5 Launching IDE

2.5.1 Pycharm

Launch the Pycharm and start creating a pure python project named HelloWorld. The screen shows the project creation.

python dictionary - Pycharm Create project
Pycharm Create project

The project settings are set in the next screen as shown below.

Python vs Java - Pycharm Project Settings
Pycharm Project Settings

Pycharm welcome screen comes up shows the progress as indicated below.

python dictionary - pycharm
Pycharm Project View

You can create a Hello.py and execute the python file by selecting the Run menu.

python dictionary - hello world
Pycharm Hello World

The output message “Hello World” is printed when the python file is Run.

Pycharm Python Execution

2.6 What is a dictionary?

You can use a dictionary for storing a set of data items. It has a key, and each key has one item associated with it. When given a key, the dictionary will restore the item related to that key. These keys can be of any data type: strings, integers, or objects. Where we need to sort a list, an element value can be found using its key. Add, remove, modify, and lookup operations are possible on this collection. A dictionary is similar to other data structures, such as hash function and hashmap. The key/value store is used in distributed caching and in-memory databases. Dictionary data structures are used in the following streams like Phone directories, Router tables in networking, Pagetables in operating systems, Symbol tables in compilers, and Genome maps in biology.

2.7 Defining a Dictionary

You can define the dictionary by using the dict() function or curly braces {}.Defining Dictionary in Python

Example_Dict = {}
print("Empty Example_Dictionary: ")
print(Example_Dict)

You can execute the above code using the command below:Execution Command

python3 Example_Dict.py

The output of the above code executed is shown below:Execution Output

apples-MacBook-Air:python_data_structures bhagvan.kommadi$ python3 Example_Dict.py 
Empty Example_Dictionary: 
{}

2.8 Accessing Dictionary Values

You can access the dictionary values by key name. You can use [] square brackets to access the value of any key as shown below:Accessing Dictionary Values in Python

Example_Dict = {}
print("Empty Example_Dictionary: ")
print(Example_Dict)
Example_Dict[0] = 'JavaCodeGeeks'
Example_Dict[2] = 'Like'
Example_Dict[3] = 2
print("\nExample_Dictionary will be like below after adding 3 elements: ")
print(Example_Dict)
print(Example_Dict[3])

You can execute the above code using the command below:Execution Command

python3 Example_Dict.py

The output of the above code executed is shown below:Execution Output

apples-MacBook-Air:python_data_structures bhagvan.kommadi$ python3 Example_Dict.py 
Empty Example_Dictionary: 
{}
 
Example_Dictionary will be like below after adding 3 elements: 
{0: 'JavaCodeGeeks', 2: 'Like', 3: 2}
2

2.9 Dictionary Keys vs. List Indices

Dictionary values can be accessed by keys. Key-value pairs are saved in the dictionary. A list is a collection of ordered elements that are used to persist a list of items. Unlike array lists, these can expand and compress dynamically. You can use Lists as a base for other data structures, such as stack and queue. You can also use them to store lists of users, car parts, ingredients, to-do items, and various other such elements. Lists are the common linear data structures used by the developers. They were first introduced in the lisp programming languageDefining Dictionary in Python

Example_Dict = {}
print("Empty Example_Dictionary: ")
print(Example_Dict)
Example_Dict[0] = 'JavaCodeGeeks'
Example_Dict[2] = 'Like'
Example_Dict[3] = 2
print("\nExample_Dictionary will be like below after adding 3 elements: ")
print(Example_Dict)

Example_Dict['Value_set'] = 4, 5, 7
print("\nExample_Dictionary will be like below after adding 3 elements: ")
print(Example_Dict)

Example_Dict[2] = 'Hello'
print("\nUpdated key value for second element: ")
print(Example_Dict[2])

# List Defintion
Example_List = []
print("Initial blank Example_List: ")
print(Example_List)


Example_List.append(1)
Example_List.append(2)
Example_List.append(7)
print("\nExample_List after Addition of Three elements: ")
print(Example_List)

print(Example_List[1])

You can execute the above code using the command below:Execution Command

python3 Example_Dict_List.py

The output of the above code executed is shown below:Dictionary vs List

apples-MacBook-Air:python_data_structures bhagvan.kommadi$ python3 Example_Dict.py 
Empty Example_Dictionary: 
{}
 
Example_Dictionary will be like below after adding 3 elements: 
{0: 'JavaCodeGeeks', 2: 'Like', 3: 2}
 
Example_Dictionary will be like below after adding 3 elements: 
{0: 'JavaCodeGeeks', 2: 'Like', 3: 2, 'Value_set': (4, 5, 7)}
 
Updated key value for second element: 
{0: 'JavaCodeGeeks', 2: 'Hello', 3: 2, 'Value_set': (4, 5, 7)}
 
Hello

Initial blank Example_List: 
[]

Example_List after Addition of Three elements: 
[1, 2, 7]
2

2.10 Restrictions on Dictionary Keys

Dictionary keys cannot be polymorphic. Its keys cannot be repeated. They are immutable. Its keys are case-sensitive. Key with different cases but same spelling are different.

2.11 Operators and Built-in Functions

Python has the following operators for Dictionary:

  • dict[key]: This operator is used to get the value based on the given key from the dictionary.
  • dict[key] = pairvalue: You can use this operator to set the value based on the given key from the dictionary.
  • del dict[key]: This operator  is used to delete the key and its paired value from the dictionary.

The table below shows the built-in functions for Dictionary:

FunctionUsage
clear()This function removes all items from the dictionary.
copy()This function returns a shallow copy of the dictionary.
fromkeys(seq[, v])This function returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d])This function returns the value of the key. If the key does not exist, returns d (defaults to None).
items()This function returns a new object of the dictionary’s items in (key, value) format.
keys()This function returns a new object of the dictionary’s keys.
pop(key[,d])This function removes the item with the key and returns its value or d if the key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem()This function removes and returns a key-value pair. It raises KeyError if the dictionary is empty.
setdefault(key[,d])This function returns the corresponding value if the key is in the dictionary. If not, it inserts the key with a value of d and returns d (defaults to None).
update([other])This function updates the dictionary with the key-value pairs from other, overwriting existing keys.
values()This function returns a new object of the dictionary’s values
Built-In Functions

3. Download the Source Code

Download
You can download the full source code of this example here: Python Dictionary with Examples

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments