Skip to content

Practical Exercises for Creating and Working with Dictionaries in Python

Updated: at 04:56 AM

Dictionaries are a powerful built-in data structure in Python that allow you to store data as key-value pairs. They provide a flexible and efficient way to organize, access and modify data for a wide range of applications. This guide will walk through practical coding exercises and examples for creating and utilizing dictionaries effectively in Python.

Table of Contents

Open Table of Contents

Introduction

A dictionary in Python is an unordered collection of keys mapped to values. Dictionaries are enclosed in curly braces { } and contain key-value pairs separated by commas. Keys can be any immutable data type like strings, numbers or tuples, while values can be of any data type.

Some key advantages of using dictionaries in Python include:

Mastering dictionary operations enables working on practical Python programming problems efficiently. This guide will cover coding exercises for common dictionary operations like creating, accessing, modifying, and processing dictionary data.

Creating Dictionaries

Dictionaries can be created and initialized in several ways:

Using Curly Braces

The dictionary keys and values can be directly specified within curly braces:

dict1 = {'key1': 'value1', 'key2': 'value2'}

Using the dict() Constructor

The dict() constructor can convert a list of tuple pairs into a dictionary:

dict2 = dict([('key1', 'value1'), ('key2', 'value2')])

From Variables

Dictionaries can be created from variables:

key1 = 'key1'
value1 = 'value1'

dict3 = {key1: value1}

From Keyword Arguments

The dict() constructor can also take keyword arguments to create dictionaries:

dict4 = dict(key1='value1', key2='value2')

Accessing Dictionary Elements

Dictionary elements can be accessed via keys using square brackets [] or the get() method.

Square Bracket Lookup

Use the key inside square brackets to retrieve the associated value:

dict = {'name': 'John', 'age': 25}

print(dict['name']) # Prints 'John'

This raises a KeyError if the key does not exist.

get() Method

The get() method allows specifying a default value to return if the key does not exist:

value = dict.get('unknown_key', 'Not Found') # Returns 'Not Found'

get() also accepts None as the default value:

value = dict.get('unknown_key') # Returns None

Modifying Dictionaries

Dictionaries are mutable, meaning elements can be added, changed or removed after creation:

Adding New Key-Value Pairs

New key-value pairs can be added just like assigning to a new index position when creating lists:

dict = {'name': 'John'}

dict['age'] = 25 # Add new key 'age'

Changing Values

Values can be changed by re-assigning existing keys:

dict = {'name': 'Sara'}

dict['name'] = 'Sam' # Changed value from 'Sara' to 'Sam'

Removing Key-Value Pairs

The del keyword or pop() method can remove a key-value pair by key:

dict = {'name': 'Mary', 'age': 25}

del dict['name'] # Removes key 'name'
dict.pop('age') # Removes key 'age' and returns the value

popitem() removes and returns an arbitrary key-value pair.

Dictionary Membership Test

Membership tests check whether a key or value exists in the dictionary:

in Operator

The in operator checks keys:

dict = {'name': 'John', 'age': 25}

print('name' in dict) # True
print('address' in dict) # False

key() and values() Methods

keys() and values() return iterable views that can be used for membership testing:

print(25 in dict.values()) # True
print('age' in dict.keys()) # True

Iterating Over Dictionaries

Dictionaries can be iterated over using for loops. By default, the loop iterates over dictionary keys:

dict = {'name': 'John', 'age': 25}

for key in dict:
    print(key) # Prints keys: 'name', 'age'

To access both keys and values, use the items() method:

for key, value in dict.items():
    print(key, ":", value)

# Prints:
# name : John
# age : 25

Dictionary Comprehensions

Dictionary comprehensions provide a concise way to create dictionaries from expressions:

values = ['John', 'Sara', 25]

dict = {f'key{i+1}': value for i, value in enumerate(values)}
print(dict) # {'key1': 'John', 'key2': 'Sara', 'key3': 25}

Common Dictionary Operations

Here are some exercises for common dictionary operations:

Count Word Frequency

Count the frequency of each word in a sentence:

sentence = "This is a common interview question"

words = sentence.split() # Split into words

freq = {}
for word in words:
    if word in freq:
        freq[word] += 1
    else:
        freq[word] = 1

print(freq) # {'This': 1, 'is': 1, 'a': 1, 'common': 1, 'interview': 1, 'question': 1}

Merge Dictionaries

Merge two dictionaries into one:

dict1 = {'name': 'John', 'age': 25}
dict2 = {'height': 175, 'weight': 80}

dict3 = {**dict1, **dict2}

print(dict3) # {'name': 'John', 'age': 25, 'height': 175, 'weight': 80}

Sort Dictionary By Value

Sort a dictionary by its values:

dict = {'banana': 3, 'apple':2, 'pear': 1, 'orange': 4}

# Method 1: Sorted() + lamda
sorted_dict = sorted(dict.items(), key=lambda x: x[1])

# Method 2: Operator module
import operator
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))

print(sorted_dict)
# [('pear', 1), ('apple', 2), ('banana', 3), ('orange', 4)]

This provides practical exercises for leveraging dictionaries to solve programming problems like counting frequencies, merging maps, sorting etc.

Applications of Dictionaries

Some real-world applications of dictionary data structures include:

User Profiles in Applications

Dictionaries can store user profile data, with keys as field names and values as the data:

user = {
  'name': 'John',
  'username': 'john123',
  'email': '[email protected]',
  'addresses': [
    {'street': '123 Main St', 'city': 'Anytown'},
    {'street': '456 Pine Rd', 'city': 'Forestville'}
  ]
}

The nested dictionary allows representing multiple addresses.

Word Count in Text Analytics

In text analytics, dictionaries can store word counts for a document with words as keys and frequencies as values:

text = "Data science is an interdisciplinary field."

word_counts = {}
for word in text.split():
    if word in word_counts:
        word_counts[word] += 1
    else:
        word_counts[word] = 1

print(word_counts)
# {'Data': 1, 'science': 1, 'is': 1, 'an': 1, 'interdisciplinary': 1, 'field.': 1}

Default Values in Functions

Function parameters can have default values defined using a dictionary:

def process(name, options={'format':'CSV', 'verbose':False}):
    # function code uses options

This allows options to be specified by name.

Cache Implementation

A dictionary can act as a simple cache storing results of expensive function calls:

# Simple cache storing calculated results
cache = {}

def fib(n):
    if n in cache:
        return cache[n] # Return cached result

    # Compute and cache result
    cache[n] = compute_fib(n)
    return cache[n]

This avoids re-computation of values.

These are some examples of how dictionaries are used in practical scenarios for data storage, text analysis, function arguments and caching.

Conclusion

Dictionaries are a versatile built-in data structure in Python that provide fast, flexible access to data using keys. This guide covered practical coding examples and exercises for creating dictionaries, accessing and modifying elements, membership testing, iteration, comprehensions and common dictionary operations like counting frequencies and sorting.

Some real-world applications were also presented like storing user profiles as dictionaries, counting word frequencies for text analytics, setting function defaults using dictionaries and simple cache implementations. Mastering dictionary usage unlocks the ability to write efficient and optimized Python code for data analysis, application development and implementing algorithms.