[Complete Guide] Python Dictionary Tutorial for Beginners

[Complete Guide] Python Dictionary Tutorial for Beginners

What is a dictionary in Python? What are the commands to perform various operations on the Dictionary?

The operation includes creating the dictionary, adding a new element, updating elements, deleting the dictionary.

Here is a complete Python dictionary tutorial for you.

At the end of this tutorial, you will also find some of the important methods you can use with the dictionary. These simple methods will make your programming go easy.

Let’s start…

What is a dictionary in Python?

It is a data structure in Python that stores the data in key-value pairs.

For example:

empAge = {'Mark': 23,  'Bob': 45}

The empAge is a dictionary object which stores an employee’s name and age in the key-value format.

  • There are two keys- ‘Mark’ and ‘Bob’.
  • The value associated with key ‘Mark’ is ’23’ which is his age.
  • The value associated with key Bob is ’45’ which is his age.

Properties / Characteristics of dictionary:

These are the simple things you should always remember while using a Python dictionary.

  • Key in the dictionary should be unique. The duplicate key is not allowed.
  • Keys must be immutable (Mutable vs Immutable). You can always delete and add a new key. But, you can not change the key.

Different Operations on Python Dictionary

How to create a dictionary in Python?

Following is the simple syntax for creating a Python dictionary.

How to create an empty dictionary?

myDict = {}

Here, myDict is the new dictionary object. You can give any name to the dictionary object.

How to create a dictionary with integer keys?

empDict = {1: 'Mark', 2: 'Bob'}

Here is the empDict object which stores the employee’s ID as a key and his name as value.

Employee ID is an integer (one of the numeric data types in Python).

How to create a dictionary with mixed key data types?

Instead of just using an integer value as a key we can also mix the data types of key.

empDict = {1: 'Mark', 'salary': 200}

In the above example, the first pair of key-value has an integer key (1). The second key-value pair has a string key (‘salary’).

How to create a dictionary using dict()?

empDict = dict({1: 'Mark', 2: 'Bob'})

Here, dict is just an extra keyword. You can use it or skip it, based on how you feel comfortable with.

However, as per the flake8 standard for writing the Python dictionary, it is recommended to use the dictionary literal ({}) instead of dict() method.

These are all different methods for creating a dictionary in Python. You can choose which suits best your requirement and feel comfortable with them.

How to access an element from the dictionary?

Every key in the dictionary is mapped to the value. So, while retrieving any value from the dictionary you have to provide key elements. And you will get a value corresponding to the key in return.

There are two ways of doing it.

Using key as indexing

print(myDict['name']) #indexing

Using get method

print(myDict.get('age')) #method

Sometimes, the key you provide in the get() method may not be present. In this case, you can set the default value for the key that is not present.

How to add a new element or update an existing element in the dictionary?

Let say we already have a dictionary with some elements in it.

empDict = {1: 'Mark', 2: 'Bob'}

Updating existing discretionary value:

If the key is already present in the dictionary, it will overwrite the value, to preserve the uniqueness of the key.

empDict = {1: 'Mark', 2: 'Bob'}
empDict[2] = 'Alice'


# Output: {1: 'Mark', 2: 'Alice'}

Adding a new element to the dictionary:

If the key is not present in the dictionary, it adds a new key-value pair in the dictionary.

empDict = {1: 'Mark', 2: 'Bob'}
empDict[3] ='Alice'


# Output: {1: 'Mark', 2: 'Bob', 3:'Alice'}

Note: The syntax for adding and updating elements in the dictionary is the same.

Adding a new element to the dictionary with the same key:

What if we try to add a new element in the dictionary with the key which is already present in the dictionary?

If you try to add the same element in the dictionary with the same keys, it overwrites the key value.

It is similar to updating the value of the given key in the dictionary.

How to delete or remove elements from the dictionary?

Let’s consider this dictionary.

# create a dictionary
squaresDict = {1:1, 2:4, 3:9, 4:16, 5:25}

How to remove a particular element from the dictionary using pop?

You have to specify the key.

Here is a way of doing this using the simple pop method.

print(squaresDict .pop(4)) 

# Output: 16

The pop method returns the value of the dictionary element you are removing.

When you print the dictionary after performing the pop operation, you don’t see that element in the dictionary.

print(squaresDict ) 

# Output: {1: 1, 2: 4, 3: 9, 5: 25}

How to remove an arbitrary item for which you know key-value pair using pop?

Use popitem method for this. You need to provide both key and value here.

print(squaresDict .popitem())
# Output: (1, 1)

# Output: {2: 4, 3: 9, 5: 25}

How to remove an element from a dictionary using del?

Just like the pop method you can also use the del object.

# delete a particular item
del squaresDict [5]

print(squaresDict )
# Output: {2: 4, 3: 9}

The keyword del is not only specific to the dictionary. It is a generic way of deleting any Python object.

Difference between del and pop method in the dictionary.

  • The del object simply delete the element from the dictionary.
  • In case of the pop method, along with deleting an element from a dictionary it also returns the value of the target element.

How to delete all the items in the dictionary?

Now we are not interested in deleting a single element. What if you want to delete the complete dictionary? Or want to clear all the elements in the dictionary?

Dictionary has a special method called clear to delete all the items from the dictionary.

squaresDict = {1:1, 2:4, 3:9, 4:16, 5:25}
squaresDict .clear() # remove all items

print(squaresDict )

# Output: {}

You can see the empty dictionary as an output.

How to Delete Complete Dictionary?

Earlier we have tried del object for deleting a particular item from the dictionary. Now you want to delete the complete dictionary object instead of just removing all elements from the dictionary.

Using a del object, you can delete the complete dictionary.

squaresDict = {1:1, 2:4, 3:9, 4:16, 5:25}
del squaresDict # delete the dictionary itself

After deleting the dictionary object, when you try to print the dictionary, it throws an error.

Difference between del and clear method:

If you delete the dictionary using del, it wipes out the complete dictionary object.

If you try to access the dictionary, it will through an error.

empDict = {1: 'Mark', 2: 'Bob'}
del empDict
Traceback (most recent call last):
File "/home/7d2f6393bbb812bde2a7f038b346bb7e.py", line 5, in
print(empDict )
NameError: name 'empDict' is not defined

It means the dictionary has been deleted.

Method clear() does not delete the dictionary. It removes all the items from the dictionary. Dictionary will be empty.

Dictionary Membership Test

What is the membership test?

Check if the key is present in the dictionary or not.

squaresDict = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

You can do the membership test using ‘in’.


<expected_key> in <dictionary_object>

It returns true if the key is present in the dictionary.

It returns false if the key is not present in the dictionary.


print(1 in squaresDict)
# Output: True

print(4 in squaresDict)
# Output: False

“not in”

You can also apply negation ‘not in’.

Slightly different. If the key is not present in the dictionary, it returns True.


print(2 not in squaresDict)
# Output: True

Iterating Through Python Dictionary

Many times you have to iterate over all the elements in the dictionary.

It is simple.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:

The above example will print all the dictionary elements one-by-one.

Inside for loop, you can write a code to perform any operations on each element of the dictionary.

You can also use the items method for iteration.

Using items methods for iterating over the dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} 
for item in squares.items(): 

How to convert Sequence to Dictionary?

How to create a dictionary from the sequence?

You can use each sequence as a key-value pair. Here is a simple code that works for you.

empDict = dict([(1,'Mark'), (2,'Bob')])

We are using the same dict() method that was used earlier for creating a dictionary object.

Python Dictionary Methods

Look at some of the methods you can use with the dictionary.

  1. clear(): Remove all items from the dictionary.
  2. copy(): Return a shallow copy of the dictionary.
  3. fromkeys(seq[, v]): Return a new dictionary with keys from seq and value equal to v (defaults to None).
  4. get(key[,d]): Return the value of key. If the key does not exist, return d (defaults to None).
  5. items(): Return a new view of the dictionary’s items (key, value).
  6. keys(): Return a new view of the dictionary’s keys.
  7. pop(key[,d]): Remove the item with a key and return its value or return ‘d’ if the key is not found. If d is not provided and the key is not found, raises KeyError.
  8. popitem(): Remove and return an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
  9. setdefault(key[,d]): If the key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).
  10. update([other]): Update the dictionary with the key/value pairs from other, overwriting existing keys.
  11. values(): Return a new view of the dictionary’s values

Let’s take some examples of dictionary methods.

Write a Python code to initialize the dictionary with zero value for all specified keys.

marks = {}.fromkeys(['Math','English','Science'], 0)

# Output: {'English': 0, 'Math': 0, 'Science': 0}

Using items methods for iterating over the dictionary.

for item in marks.items():

Using the keys method to get all the keys present in the dictionary.


# Output: ['English', 'Math', 'Science']

Python Dictionary List Comprehension

You can use the comprehension technique to generate the dictionary items.

Write a python code to store the square as the value for each key.

squares = {x: x*x for x in range(6)}

# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This is simply equivalent to the following code.

squares = {}
for x in range(6):
    squares[x] = x*x

We can add some more conditions to the comprehension technique.

odd_squares = {x: x*x for x in range(11) if x%2 == 1}

# Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Built-in Functions with Dictionary

There are also some built-in functions you can use with a dictionary.

  1. all(): Return True if all keys of the dictionary are true (or if the dictionary is empty).
  2. any(): Return True if any key of the dictionary is true. If the dictionary is empty, return False.
  3. len(): Return the length (the number of items) in the dictionary.
  4. cmp(): Compares items of two dictionaries.
  5. sorted(): Return a new sorted list of keys in the dictionary.

Let’s check some examples.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

How to find the length of the dictionary (number of items in the dictionary.)

print(len(squares)) # Output: 5

How to sort the items in the dictionary by key?

print(sorted(squares)) # Output: [1, 3, 5, 7, 9]

Other Python Dictionary Tutorials:

This is all about the complete Python dictionary tutorial. If you have any specific questions to discuss, write our query in the comment.

Happy Pythoning!


  1. Well done! That’s the clearest and most comprehensive intro to dictionaries I’ve seen!

    I’ll be looking out for your other tutorials!

  2. You gave some examples and then makes a list of dictionary methods. “get” method is great. It also deserves for example. And the comprehension part showed me something that I didn’t see until now. Thanks.

  3. Wow! That is all I can say. Your examples and explanations are so concise. I really enjoyed how you show different methods for solving the same problem. You did a lot of work organizing this and I will share with everyone I know. Thank You!

Leave a Reply

Your email address will not be published. Required fields are marked *