Python Dictionary

In this article we are discussing Python Dictionary with the help of many examples. You will learn to create dictionary in Python and then perform various operations on it.

Python Dictionary

Python Dictionary - Create, Update, Access and Clear dictionary object

In this section we are going to learn everything you should learn to master Python Dictionary. We are going to teach you dictionary with many examples and small code snippets. We will also provide details of various methods of dictionary in Python. Let's get started with the Python Dictionary data structure.

What is Python Dictionary?

Dictionary is one of the data structure in Python which is un-ordered and used to store data in key/value pair. List in Python contains only data while dictionary contains data in the form of key/value pair. In dictionary you can access the data by providing the key to dictionary object. If dictionary objet finds the key inside it, then it returns the value for provided key. Dictionary is designed and optimized to retrieve values by key from the dictionary object. In this section we are going to discuss Python dictionary in detail with many examples.

Python Dictionary

Creating Dictionary in Python?

Now we will see how to create a dictionary object in Python. In Python dictionary object is created with the help of curly braces {}. To create dictionary you can pass the key-value pair inside the curly braces separated by comma.

Here is simple example of creating dictionary in Python:

book_dict = {"name":"Python Book", "price":"100"}

If you print the book_dict it will give following output:

>>> book_dict = {"name":"Python Book", "price":"100"}
>>> print(book_dict)
{'name': 'Python Book', 'price': '100'}

If you can to create an empty dictionary then you can create with following code:

my_empty_dict = {}

You can create empty dictionary object to add data in later point of time during programming.

This is the simple example of creating dictionary in Python. Now let's look at other methods of creating dictionary.

Python dictionary with mixed keys

You can create dictionary with mixed keys in following way:

book_dict = {"name":"Python Book", "price":"100",
	"authors":["Deepak Kumar","Tom","John"]}


If you run the above code it will show following output:

>>> book_dict = {"name":"Python Book", "price":"100",
...     "authors":["Deepak Kumar","Tom","John"]}
>>> print(book_dict)
{'name': 'Python Book', 'price': '100', 'authors': ['Deepak Kumar', 'Tom', 'John']}

Creating dictionary with dict() function

In Python you can also use the dict() function to create dictionary. You can pass the key value pairs as parameter to the dict() function and it will create dictionary object with the data passed as argument. Here is example of creating dictionary using dict() function:

book_dict = dict(name= "Python Book", price="200")

Here is the output of program:

>>> book_dict = dict(name= "Python Book", price="200")
>>> print(book_dict)
{'name': 'Python Book', 'price': '200'}

You can also pass the items in pairs as shown below:

book_dict = dict([("name", "Python Book"),("price","200")])

We have seen various ways to create dictionary object in Python. Now we will see how to access the items inside it.

Accessing elements inside dictionary

Now we will see how to access the elements inside the dictionary. You can get the data stored in dictionary with the help of get() method or square brackets [] if you know the key. But if you don't know the key then iterate over all the keys to get data.

Here is example of getting dictionary data with get() method and square brackets[]:

book_dict = dict([("name", "Python Book"),("price","200")])



Here is the output of program:

>>> book_dict = dict([("name", "Python Book"),("price","200")])
>>> print(book_dict.get("name"))
Python Book
>>> print(book_dict["name"])
Python Book

There is one difference between get() function and getting values with square brackets. The get() method returns None if key is not found whereas [] way of getting returns KeyError as shown below:

>>> print(book_dict.get("name1"))
>>> print(book_dict["name1"])
  File "", line 3
ntaxError: invalid syntax

Python Dictionary Methods

Now we will see the methods of the dictionary in Python. Here are the built-in methods of dictionary that you can use while developing your program:

clear() - The clear() method is used to remove all the elements from dictionary object.

copy() - The copy() method is used to create a copy of dictionary.

fromkeys() - This method is used to create a new dictionary from existing dictionary picking up the key and its values provides as parameter.

get() - The get() method is used to return the value of the specified key.

items() - The items() method returns a list in the key value tuple pair.

keys() - The keys() function returns a list of keys in the dictionary which further can be used to iterate over the values in the dictionary.

pop() - The pop() method is used to remove the element by key from dictionary.

popitem() - This method is used to remove the last inserted key-value pair from the dictionary.

setdefault() - Is used to update the value of a key in the dictionary.

values() - The method is used to return a list of all the values stored in the dictionary object. 0

Iterating key and values of a dictionary

Now here is simple program for iterating all the key/values stored in the dictionary and printing on the console:

for k, v in book_dict.items():

Here is the output of program:

>>> for k, v in book_dict.items():
...     print(k,v)
name Python Book
price 200

In this section we have learned python dictionary and understood different ways to create dictionary. We have learned to get the data from dictionary and print on the console. We have explains various methods of dictionary in Python. Python dictionary provides various methods to work with it. You can easily get the values with the help of get() method or get list of all the keys using keys() function. The dictionary API provides methods to remove an element from the dictionary. You can also use the copy() method to create another copy of existing dictionary. 1

Check more tutorials at Python Tutorials.