tech beamers
  • Python Lab
    • Python Online Compiler
    • Python Code Checker
    • Python Coding Exercises
    • Python Coding Quizzes
  • SQL Practice
  • SQL Prep
  • Selenium Practice
  • Software Testing
tech beamers
Search
  • Python Lab
    • Python Online Compiler
    • Python Code Checker
    • Python Coding Exercises
    • Python Coding Quizzes
  • SQL Practice
  • SQL Prep
  • Selenium Practice
  • Software Testing
Follow US
© TechBeamers. All Rights Reserved.
Python Exercises

Python Dictionary Exercises

Last updated: Apr 18, 2025 3:20 pm
Harsh S.
By Harsh S.
No Comments
8 months ago
SHARE

Presenting today is a tutorial covering some of the best Python dictionary examples. We believe it is a valuable resource for anyone who wants to learn more about this important data structure.

Contents
  • Practice with the Best Python Dictionary Examples
  • What is a Python Dictionary?
  • Best Python Dictionary Examples
    • Write a function that takes a dict as input and returns a list of all the unique values in the dict .
    • Write a function that takes two dicts as input and merges them into a single dict , overwriting any duplicate keys.
    • Write a function that takes a dict as input and returns a dict with the keys and values reversed.
    • Write a function that takes a list of strings as input and returns a dict with each string as a key and its count as the value.
    • Write a function that takes a dict as input and returns a list of all the keys that have a value greater than a certain threshold.
    • Write a function that takes an OrderedDict as input and returns a list of all the keys in the OrderedDict in the order that they were inserted.
  • Essential Python Dictionary Techniques
  • Takeaways from Python Dictionary Examples

The tutorial provides a clear and concise overview of Python dictionaries, including their key features and common uses. It also includes a variety of examples, which are well-explained and easy to follow.

Python Dictionary Guide →

Practice with the Best Python Dictionary Examples

Before we start, look at some specific benefits that you can gain from the tutorial:

  • Learn what Python dictionaries are and how to use them.
  • Understand the different types of Python dictionaries and their purposes.
  • Learn how to create, access, and modify Python dictionaries.
  • Learn how to use Python dictionaries to solve a variety of problems.

First of all, the following is an important question that you must clearly understand.

What is a Python Dictionary?

Python dictionaries store key-value pairs, which are data structures that map keys to values. Additionally, dictionaries can store any immutable object as a key, such as strings, numbers, or tuples. They can also store any Python object as a value, such as strings, numbers, lists, or dictionaries.

Unordered dictionaries do not guarantee the order in which the key-value pairs are stored. Additionally, dictionaries are mutable, meaning that the values in a dictionary can change after it is created.

Convert a Dict to JSON →

There are two ways to create a Python dictionary:

⌬ Using curly braces ({})

my_dict = {}

⌬ Using the dict() function:

my_dict = dict()

To add key-value pairs to a dictionary, you can use the following syntax:

my_dict["key"] = "value"

Best Python Dictionary Examples

Let’s explore various examples of Python dictionaries categorized by common use cases to help you grasp the concept easily.

Write a function that takes a dict as input and returns a list of all the unique values in the dict .

Dict to DataFrame →
def get_unique_values(dict1):
  """Returns a list of all the unique values in the given dictionary.

  Args:
    dict1: A dictionary.

  Returns:
    A list of all the unique values in dict1.
  """

  unique_values = set()
  for value in dict1.values():
    unique_values.add(value)
  return list(unique_values)


# Example usage:

dict1 = {"apple": "a fruit", "banana": "another fruit", "orange": "another fruit"}
unique_values = get_unique_values(dict1)
print(unique_values)

Output:

['a fruit', 'another fruit']

Write a function that takes two dicts as input and merges them into a single dict , overwriting any duplicate keys.

Append to a Dict →
def merge_dicts(dict1, dict2):
  """Merges two dictionaries into a single dictionary, overwriting any duplicate keys.

  Args:
    dict1: A dictionary.
    dict2: A dictionary.

  Returns:
    A new dictionary with the merged contents of dict1 and dict2.
  """

  merged_dict = dict1.copy()
  merged_dict.update(dict2)
  return merged_dict


# Example usage:

dict1 = {"apple": "a fruit", "banana": "another fruit"}
dict2 = {"orange": "another fruit", "pear": "another fruit"}
merged_dict = merge_dicts(dict1, dict2)
print(merged_dict)

Output:

{'apple': 'a fruit', 'banana': 'another fruit', 'orange': 'another fruit', 'pear': 'another fruit'}

Write a function that takes a dict as input and returns a dict with the keys and values reversed.

Search Keys in Dictionary →
def reverse_dict(dict1):
  """Reverses the keys and values of a dictionary.

  Args:
    dict1: A dictionary.

  Returns:
    A new dictionary with the keys and values reversed.
  """

  reversed_dict = {}
  for key, value in dict1.items():
    reversed_dict[value] = key
  return reversed_dict


# Example usage:

dict1 = {"apple": "a fruit", "banana": "another fruit"}
reversed_dict = reverse_dict(dict1)
print(reversed_dict)

Output:

{'a fruit': 'apple', 'another fruit': 'banana'}

We hope the above examples are helpful!

Here are some more Python dict examples with their solutions that the interviewer can ask to solve using dictionaries only:

Write a function that takes a list of strings as input and returns a dict with each string as a key and its count as the value.

Solution:

def count_strings(str_list):
  """Returns a dictionary with each string in str_list as a key and its count as the value.

  Args:
    str_list: A list of strings.

  Returns:
    A dictionary with each string in str_list as a key and its count as the value.
  """

  str_counts = {}
  for str in str_list:
    if str in str_counts:
      str_counts[str] += 1
    else:
      str_counts[str] = 1
  return str_counts


# Example usage:

str_list = ["apple", "banana", "apple", "orange", "apple"]
str_counts = count_strings(str_list)
print(str_counts)

Output:

{'apple': 3, 'banana': 1, 'orange': 1}

Write a function that takes a dict as input and returns a list of all the keys that have a value greater than a certain threshold.

Solution:

def get_keys_with_value_greater_than_threshold(dict1, threshold):
  """Returns a list of all the keys in dict1 that have a value greater than threshold.

  Args:
    dict1: A dictionary.
    threshold: A value.

  Returns:
    A list of all the keys in dict1 that have a value greater than threshold.
  """

  keys_with_greater_value = []
  for key, value in dict1.items():
    if value > threshold:
      keys_with_greater_value.append(key)
  return keys_with_greater_value


# Example usage:

dict1 = {"apple": 10, "banana": 5, "orange": 20}
threshold = 10
keys_with_greater_value = get_keys_with_value_greater_than_threshold(dict1, threshold)
print(keys_with_greater_value)

Output:

['apple', 'orange']

Write a function that takes an OrderedDict as input and returns a list of all the keys in the OrderedDict in the order that they were inserted.

OrderedDict Guide →
from collections import OrderedDict

def get_keys(or_dict):
  """Returns a list of all the keys in the given OrderedDict in the order that they were inserted.

  Args:
    or_dict: An OrderedDict.

  Returns:
    A list of all the keys in or_dict in the order that they were inserted.
  """

  keys_in_order = []
  for key, value in or_dict.items():
    keys_in_order.append(key)
  return keys_in_order

# Example usage:

or_dict = OrderedDict([("apple", "a fruit"), ("banana", "another fruit"), ("orange", "another fruit")])
keys_in_order = get_keys(or_dict)
print(keys_in_order)

We hope solving these problems was worth it and helped you gain some knowledge.

Python dicts are versatile and can be applied to various scenarios. They provide a convenient way to store and manipulate data in a key-value format. With these examples, you should be well on your way to using dictionaries effectively in your Python programs.

Essential Python Dictionary Techniques

View Guide

Takeaways from Python Dictionary Examples

In conclusion, we hope this article has been helpful. I have provided solutions to five common Python interview problems using dictionaries only.

These problems are all relatively short, but they cover a variety of important concepts, such as getting unique values, merging dictionaries, reversing dictionaries, counting strings, and getting keys with values greater than a certain threshold.

We encourage you to practice solving these problems on your own to solidify your understanding of dictionaries and Python programming in general.

Happy Coding!

Related

Share This Article
Whatsapp Whatsapp LinkedIn Reddit Copy Link
Harsh S. Avatar
ByHarsh S.
Follow:
Harsh S., MCA graduate, has 8+ years leading development on IT projects, specializing in Python, Java, unit testing, and CI/CD. At TechBeamers, Harsh authors tutorials, quizzes, and exercises on programming and AI/Data Science.
Previous Article 20 Pattern Programs in Python Python Pattern Programs Exercises
Next Article 10 Python Beginner Projects with Full Code Python Small Projects for Beginners
Leave a Comment

Leave a Reply

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

Most Popular This Month

  • → Python Online Compiler
  • → Python Code Checker
  • → Free Python Tutorial
  • → SQL Practice Queries
  • → Code to Flowchart Tool
  • → Python Syntax Guide
  • → Python List & Dict Questions
  • → Selenium Practice Test Page

RELATED TUTORIALS

4 ways to find all possible string permutation in Python

Python Program: Find Possible Permutation of a String

By Harsh S.
4 weeks ago
Python Sort a List in Descending Order With Examples

Python Program: Sort List in Descending Order

By Soumya Agarwal
4 weeks ago
Count frequency of each word in a Python string

Python Program: Compute Frequency of Each Word

By Meenakshi Agarwal
4 weeks ago
Multiple Ways to Iterate Strings in Python

Python Program: 5 Ways to Iterate Strings

By Meenakshi Agarwal
4 weeks ago
© TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
Advertisement