• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Complete Guide] Python Dictionary Tutorial for Beginners

Aniruddha Chaudhari/23412/8
CodePython

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…

Table of Contents

  • What is a dictionary in Python?
  • Different Operations on Python Dictionary
    • How to create a dictionary in Python?
    • How to access an element from the dictionary?
    • How to add a new element or update an existing element in the dictionary?
    • How to delete or remove elements from the dictionary?
    • Difference between del and pop method in the dictionary.
    • How to delete all the items in the dictionary?
    • Dictionary Membership Test
    • Iterating Through Python Dictionary
    • How to convert Sequence to Dictionary?
  • Python Dictionary Methods
  • Python Dictionary List Comprehension
  • Built-in Functions with Dictionary

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'

print(empDict)

# 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'

print(empDict)

# 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)

print(squaresDict)
# 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
print(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’.

Syntax:

<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.

Example:

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.

Example:

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:
    print(squares[i])

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(): 
    print(item)

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)
print(marks)

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

Using items methods for iterating over the dictionary.

for item in marks.items():
    print(item)

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

list(sorted(marks.keys()))

# 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)}
print(squares)

# 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}
print(odd_squares)

# 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:

  • Set Default Value in Dictionary
  • Remove all 0 from a dictionary

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!

Python Interview Questions eBook

PythonPython Dictionary
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Jane Mycock
    April 7, 2019 at 5:58 pm

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

    I’ll be looking out for your other tutorials!

    • Reply
      Aniruddha Chaudhari
      April 20, 2019 at 11:52 am

      Thank you so much, Jane, for your kind words! Glad you like it and find it useful.

  • Reply
    Marek Szkotnicki
    April 20, 2019 at 11:47 am

    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.

    • Reply
      Aniruddha Chaudhari
      April 20, 2019 at 11:50 am

      You’re welcome, Marek! And I’m very much glad you like it. I hope you enjoy other tutorials as well. Stay connected 🙂

  • Reply
    Christopher Buck
    April 20, 2019 at 11:53 am

    Thank you very good

    • Reply
      Aniruddha Chaudhari
      April 20, 2019 at 11:54 am

      You’re welcome!

  • Reply
    David
    June 24, 2020 at 11:12 am

    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!

    • Reply
      Aniruddha Chaudhari
      June 24, 2020 at 8:14 pm

      Thanks, David for your kind words! This encourages me to write more and share it with you all. I would love it if you give me your two minutes and share your feedback/testimonial https://www.csestack.org/feedback/ . Love!

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard