Skip to content

Latest commit

 

History

History
554 lines (368 loc) · 13.5 KB

09.Dict.md

File metadata and controls

554 lines (368 loc) · 13.5 KB

Lesson 9: Data Structures p.4 (dict)

Can't come up with a quote :) But dicts rules, yeah!

Content

  1. Introduction to dict
  2. Functions and Methods of dict
  3. Iterations
  4. Quiz
  5. Homework

1. Introduction to dict

In Python, a dictionary is a mutable, unordered collection of items. While other compound data types have only value as an element, a dictionary has a key-value pair.

Dictionaries are optimized to retrieve values when the key is known. Consider them as a mini database for your application.

1.1 Syntax

Creating a dictionary is as simple as placing items inside curly braces {} separated by commas or using dict() function. An item has a key and a corresponding value that is expressed as a pair (key: value).

Example

# Option 1: Explicitly define a ``dict`` object
my_dict = {
    'name': 'John',
    'age': 30,
    'occupation': 'developer'
}

# Option 2: Pass keyword parameters
my_dict = dict(name='John', age=30, occupation='developer')

Output

{'name': 'John', 'age': 30, 'occupation': 'developer'}

Or you can create an empty dictionary:

Example

my_dict = {}
my_dict = dict()

print(my_dict)

Output

{}

1.2 Accessing and Modifying Dictionary

Accessing elements can be done by referring to its key name, enclosed in square brackets [] or using the .get() method. Adding or modifying elements can be done by using the assignment operator (=) along with the key in square brackets.

Example

my_dict = {
    'name': 'John',
    'age': 30,
    'occupation': 'developer'
}

# Access
print(my_dict['name'])
print(my_dict.get('age'))  # 30

# Modify
my_dict['age'] = 31

# Add new key-value
my_dict['hobby'] = 'painting'

print(my_dict)

Output

John
30
{'name': 'John', 'age': 31, 'occupation': 'developer', 'hobby': 'painting'}

2. Functions and Methods of dict

2.1 min() and max()

The min() and max() functions can be used with dictionaries to find the minimum or maximum key or value.

Note: By default, these functions operate on the dictionary keys, but you can specify to operate on the values by using the key parameter.

Example

Finding minimum and maximum keys

my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
print(min(my_dict))  # Output: 'apple'
print(max(my_dict))  # Output: 'cherry'

Output

apple
cherry

Example

Finding minimum and maximum values, instead of keys.

my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
print(min(my_dict.values()))
print(max(my_dict.values()))

Output

2
5

2.2 sorted()

The sorted() function returns a new sorted list from the items in any iterable. When used with dictionaries, you can sort by keys or values.

Example

my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
sorted_keys = sorted(my_dict)
print(sorted_keys)  

IMPORTANT: Output - is a list: ['apple', 'banana', 'cherry']

Output

['apple', 'banana', 'cherry']

2.3 Methods of Dictionary

Method Description Example Code Example Output
keys() Returns a view object containing the keys of the dictionary. my_dict.keys() dict_keys(['name', 'age', 'occupation'])
values() Returns a view object containing the values of the dictionary. my_dict.values() dict_values(['John', 30, 'developer'])
items() Returns a view object containing a tuple for each key-value pair. my_dict.items() dict_items([('name', 'John'), ('age', 30), ('occupation', 'developer')])
update() Updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. my_dict.update({'hobby': 'painting'}) {'name': 'John', 'age': 30, 'occupation': 'developer', 'hobby': 'painting'}
pop() Removes a specified key and returns the corresponding value. removed_age = my_dict.pop('age') Removes 'age' from my_dict and returns 30
clear() Removes all items from the dictionary. my_dict.clear() my_dict becomes {}

3. Iterations

Iterating over dictionaries can be done in several ways, such as by iterating over keys, values, or both.

3.1 Iterating Over Keys

Iterating over keys is the default behavior when iterating through a dictionary directly in a for loop.

Example

for key in my_dict:
    print(f"Key: {key}")

Output

Key: name
Key: age
Key: occupation

3.2 Iterating Over Values

If you're only interested in values, use the .values() method.

Example

for value in my_dict.values():
    print(f"Value: {value}")

Output

Value: John
Value: 30
Value: developer

3.3 Iterating Over Items

To get both keys and values simultaneously, use the .items() method. This method is particularly useful when you need to work with both elements.

Example

for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

Output

Key: name, Value: John
Key: age, Value: 30
Key: occupation, Value: developer

3.4 Using Dictionary Comprehensions

Dictionary comprehensions are not just for creating dictionaries; they can also be used to iterate over an existing dictionary.

Example

Filter out items where the value is below a certain threshold. This is useful for data processing where you only want to keep items that meet certain criteria.

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4}
filtered_dict = {key: value for key, value in my_dict.items() if value > 2}
print(filtered_dict)

Output:

{'cherry': 3, 'date': 4}

Example

Inverting the keys and values of a dictionary can be useful in scenarios where you need to look up keys by their associated values.

my_dict = {'apple': 1, 'banana': 2, 'cherry': 

3, 'date': 4}
inverted_dict = {value: key for key, value in my_dict.items()}
print(inverted_dict)

Output:

{1: 'apple', 2: 'banana', 3: 'cherry', 4: 'date'}

3.5 Iterating with enumerate()

While enumerate() is typically used with lists, it can also be applied to the .items() of a dictionary to get both the index and the key-value pairs during iteration. Not sure, where it can be applicable, but just FYI that such option exists.

Example

for index, (key, value) in enumerate(my_dict.items()):
    print(f"Index: {index}, Key: {key}, Value: {value}")

Output

Index: 0, Key: name, Value: John
Index: 1, Key: age, Value: 30
Index: 2, Key: occupation, Value: developer

4 Dictionary Equality

4.1 Equality (==)

Two dictionaries are considered equal if:

  • They have the same set of keys.
  • Corresponding keys have the same values.

Python checks each key-value pair during comparison, making it an efficient process.

Example

dict_a = {'name': 'Alice', 'age': 25, 'city': 'Wonderland'}
dict_b = {'age': 25, 'city': 'Wonderland', 'name': 'Alice'}

print(dict_a == dict_b)

Output

True

NOTE: Although dict_a and dict_b were defined in different orders, they are considered equal.

NOTE: Order does not matterm since Python 3.7, dictionaries maintain the insertion order of items. However, the order does not influence the outcome of equality comparisons.

4.2 Inequality (!=)

The inequality operator returns True if the dictionaries differ in at least one key or value.

Example

dict_a = {'name': 'Alice', 'age': 25}
dict_b = {'name': 'Alice', 'age': 30}

# The values for the key 'age' are different, so dict_a and dict_b are not equal.
print(dict_a != dict_b)

Output

True

Note: Deep comparison, the comparison is "deep" meaning nested dictionaries will also be compared accurately.

5. Nested Dictionaries

Nested dictionaries allow you to store and organize complex data structures.

5.1 Accessing Elements

To access elements within a nested dictionary, you chain square brackets [] or use the .get() method for safer access.

Example

family = {
    'john': {'age': 30, 'job': 'developer'},
    'jane': {'age': 28, 'job': 'designer'}
}

print(family['john']['job'])

Output

developer
28

5.2 Modifying Elements

Specify the keys to the path of the item you want to modify.

Example
# Modifying Jane's job
family['jane']['job'] = 'architect'

print(family['jane']['job'])

Output

architect

5.3 Adding Values

Adding a new key-value pair to a nested dictionary might require ensuring that the parent dictionary exists.

This can be done using the .setdefault() method or checking for the existence of the key.

Example

# Adding a new key-value pair for John
family['john']['hobby'] = 'painting'

# Adding a new nested dictionary for a new family member
family['alice'] = {'age': 24, 'job': 'engineer'}

print(family)

Output

{'john': {'age': 30, 'job': 'developer', 'hobby': 'painting'}, 
'jane': {'age': 28, 'job': 'designer'}, 
'alice': {'age': 24, 'job': 'engineer'}
}

5.4 Iterations

To access keys and values, you might iterate over the outer dictionary and then over each nested dictionary.

Example

for person, details in family.items():
    print(f"Name: {person}")
    for key, value in details.items():
        print(f"  {key.capitalize()}: {value}")

Output

Name: john
  Age: 30
  Job: developer
Name: jane
  Age: 28
  Job: designer

5.5 Deleting Items

To remove items either from default or a nested dictionary, use the del statement or the .pop()

Example

# Deleting a key-value pair
del family['john']['hobby']

# Removing an entire nested dictionary
removed_person = family.pop('alice', None)
print(f"Removed: {removed_person}")

Output

{'john': {'age': 30, 'job': 'developer'}, 'jane': {'age': 28, 'job': 'designer'}}
Removed: {'age': 28, 'job': 'designer'}

7. Quiz

Question 1:

What does the pop() method do in a Python dictionary?

A) Adds a new item to the dictionary
B) Returns the value of a key and removes the key-value pair from the dictionary
C) Sorts the dictionary
D) None of the above


Question 2:

How do you access the value associated with the key 'occupation' in the dictionary my_dict?

A) my_dict(occupation)
B) my_dict['occupation']
C) my_dict.get(occupation)
D) my_dict.get('occupation')


Question 3:

Which of the following statements about dictionaries in Python is true?

A) Dictionaries are ordered collections of items.
B) A dictionary's keys can be mutable types.
C) Dictionaries can contain mixed data types for keys and values.
D) A dictionary cannot contain another dictionary as a value.


Question 4:

How would you create a new dictionary that contains all the items from dict1 and dict2, where items in dict2 overwrite items in dict1 for matching keys?

A) dict1.update(dict2)
B) {**dict1, **dict2}
C) dict1 + dict2
D) dict2.update(dict1)


Question 5:

Which method would you use to safely retrieve a value from a dictionary, providing a default value if the key does not exist?

A) fetch()
B) get()
C) retrieve()
D) pull()

8. Homework

Task 1 Movie Recommendation System

Objective: Create a simple movie recommendation system that suggests movies to users based on their preferences.

Requirements:

  1. Movie Database: Create a dictionary named movie_database where keys are movie titles and values are lists containing the genre(s) of each movie.

  2. Recommendation Algorithm: Suggest a movie to a user based on their preferred genres and the movie database.

The format should be something like this:

movie_database = {
    "Interstellar": ["Adventure", "Drama", "Sci-Fi"]
}

Task 2: Quiz Game

Objective: Create a flashcard quiz game that helps users learn and test their knowledge on various topics.

Requirements:

  1. Data: Define a dictionary named flashcards where keys are questions and values are answers.

  2. Quiz: Implement a quiz functionality that presents users with a random flashcard question and prompts them to input their answer.

  3. Repeat: Allow the user to continue the quiz until they decide to quit.

flashcards = {
    "What is the chemical simbol for water?": "H2O",
}

# We haven't learnt modules yet, but you will need to figure out how to get the random question from ``flashcards``, I believe in you!