Dictionaries in Python

Dictionaries are an important data structure in Python that allow you to store and retrieve data in key-value pairs. In this article, we will explore dictionaries in Python, covering dictionary creation, accessing values, modifying dictionaries, dictionary methods, dictionary comprehension, and providing practice exercises to reinforce your understanding.

1. Creating Dictionaries:

Dictionaries in Python are created by enclosing comma-separated key-value pairs within curly braces { }. Each key-value pair is separated by a colon :.

Example:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print("Dictionary:", my_dict)

Output:

Dictionary: {'name': 'John', 'age': 25, 'city': 'New York'}

2. Accessing Values in Dictionaries:

You can access values in a dictionary by using the corresponding key inside square brackets [ ]. If the key is not present, it will raise a KeyError. Alternatively, you can use the get() method to retrieve values, which returns None if the key is not found.

Example:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print("Name:", my_dict['name'])
print("Age:", my_dict.get('age'))

Output:

Name: John
Age: 25

3. Modifying Dictionaries:

Dictionaries are mutable, meaning you can add, update, and delete key-value pairs. You can assign a new value to an existing key or add a new key-value pair by assigning a value to a new key.

Example:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict['age'] = 26
my_dict['country'] = 'USA'
del my_dict['city']

print("Modified Dictionary:", my_dict)

Output:

Modified Dictionary: {'name': 'John', 'age': 26, 'country': 'USA'}

4. Dictionary Methods:

Python provides various built-in methods specifically for dictionaries. These methods offer functionality like adding items, removing items, accessing keys, values, and items, and more.

Example:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()

print("Keys:", keys)
print("Values:", values)
print("Items:", items)

Output:

Keys: dict_keys(['name', 'age', 'city'])
Values: dict_values(['John', 25, 'New York'])
Items: dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])

5. Dictionary Comprehension:

Similar to list comprehension, dictionary comprehension allows you to create dictionaries in a concise manner using a single line of code.

Example:

numbers = [1, 2, 3, 4, 5]
squared_dict = {num: num**2 for num in numbers}

print("Squared Dictionary:", squared_dict)

Output:

Squared Dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Practice Exercises:

  1. Write a program that takes two dictionaries as input and combines them into a single dictionary, keeping unique keys and updating values if the keys already exist.
  2. Create a dictionary of student names and their corresponding grades. Write a program that asks the user for a student name and displays their grade.
  3. Given a dictionary, write a program that finds the key with the maximum value.
  4. Write a program that takes a list of dictionaries as input and sorts the list based on a specific key in each dictionary.
  5. Create a dictionary of words and their frequencies. Write a program that finds the word with the highest frequency.

Conclusion:

Dictionaries in Python provide a powerful way to store and access data using key-value pairs. Understanding how to create dictionaries, access values, modify dictionaries, use dictionary methods, and leverage dictionary comprehension will enhance your Python programming skills. By practicing the provided exercises, you can solidify your knowledge and proficiency with dictionaries in Python.

If you want to join our programmers community for daily coding practice content, join our Whatsapp Group and also Signup on Website 

2 thoughts on “Dictionaries in Python”

Leave a Comment