11.2.5.1 create a dictionary
11.2.5.2 search for data in a dictionary for a given key
Python. Dictionaries
We already know how to store data in indexed data structures such as lists.
But if we need to search for data in an explanatory dictionary or an English-Russian dictionary, then the way to store data in a list will not be very convenient.
In Python, the Dictionary data structure is used for this. Dictionaries are one of the core data structures in Python. A dictionary contains key-value pairs. A value can easily be accessed via its key.
You can access values in a dictionary by using the keys, for example:
print(my_dict['key1']) # Output: 'value1'
A dictionary is a mutable, iterated, and unordered data structure, that can be indexed by keys.
Dictionary keys can only be immutable data types. In Python, these are numbers, strings, and tuples.
Usually, the same type of data is used in one dictionary.
For example, the English-Russian dictionary of colors can be written as follows
colors = {'white': 'белый', 'red': 'красный', 'green': 'зеленый', 'blue': 'синий', 'black': 'черный'}
del colors['white']
del colors['black']
print(colors) # {'red': 'красный', 'green': 'зеленый', 'blue': 'синий'}colors = {'white': 'белый', 'red': 'красный', 'green': 'зеленый', 'blue': 'синий', 'black': 'черный'}
colors.pop('white') # delete element with key 'white'
deleted_element = colors.pop('black') # remember deleted element with index 'black'
print(colors) # {'red': 'красный', 'green': 'зеленый', 'blue': 'синий'}
print(deleted_element) # output черный
Checking if an element exists in a dictionary
colors = {'white': 'белый', 'red': 'красный', 'green': 'зеленый', 'blue': 'синий', 'black': 'черный'}
if 'red' in colors: # Checks if a word 'red' exists in a dictionary
print('Dictionary has word: red')colors = {'white': 'белый', 'red': 'красный', 'green': 'зеленый', 'blue': 'синий', 'black': 'черный'} if 'yellow' not in colors: print('Dictionary has not this word')
Methods of dictionary
Notes: d - dictionary
Function/ Method
Example
Description
d.get(key)
d.get(key, other value)
d = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
value = d.get('B')
print(value) # output 66
value = d.get('E', 'Not exist')
print(value) # output Not exist
In addition to the key, this method can also use the second parameter, in which you can display a message if the key is not in the dictionary. In this case, the program will not display an error.
All dictionary keys can be iterated with a for loop
ascii_code = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
for letter in ascii_code:
print(letter, ascii_code[letter]) # Output:
# A 65
# B 66
# C 67
# D 68
or with method keys()
ascii_code = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
for letter in ascii_code.keys():
print(letter, ascii_code[letter]) # Output:
# A 65
# B 66
# C 67
# D 68
Task. Given a long list of integers numbers. We know that some numbers appear more than once in this list. You need to find out exactly how many times each of the numbers occurs and write the data into a dictionary.
nums = [5, 7, 5, 6, 7, 12, 7, 2, 2, 5, 12, 7]
counts = {} # creating empty dictionary
for num in nums: # iterate all numbers
counts[num] = counts.get(num, 0) + 1 # increment value with key
print(counts) # {5: 3, 7: 4, 6: 1, 12: 2, 2: 2}
Name four features of a data structure Dictionary.
Explain cases when we can use Dictionaries. Give two examples.
What does each element of the dictionary consist of?
How to iterate the dictionary by keys, values, and elements?
Exercises:
Ex. 1 "Dictionary. Check yourself"
1. True or False: Dictionaries are ordered collections of key-value pairs in Python.
2. How do you create a dictionary in Python?
3. How do you access a value in a dictionary by its key?
4. How do you add a new key-value pair to a dictionary?
5. How do you delete a key-value pair from a dictionary?
6. How do you check if a key or value exists in a dictionary?
7. How do you iterate through a dictionary and access both the keys and values?
8. How do you merge two or more dictionaries into one?
9. How do you get the number of key-value pairs in a dictionary?
Answers:
1. False
2. curly braces {} and specifying key-value pairs, separated by a colon.
3. dict_name[key]
4. dict_name[new_key] = new_value
5. del dict_name[key]
6. key in dict_name
7. for key, value in dict_name.items():
8. dict1.update(dict2)
9. len(dict_name)
Tasks:
Task 1. Create a dictionary that stores the names and ages of 5 people. Write a program that prompts the user for a name, and then returns the age of that person if the name exists in the dictionary.
Task 2. Write a program that takes a list of integers as input and returns a dictionary with the integers as keys and their squares as values.
Task 3. Write a program that reads a file and creates a dictionary where the keys are words in the file and the values are the number of occurrences of that word.
Task 4. Write a program that creates a dictionary of student names and grades, where the keys are student names and the values are lists of their grades. The program should then prompt the user for a student name and return the average grade for that student.
Task 5. Create a dictionary that represents a menu of a restaurant. The keys are dish names and the values are the prices of the dishes. Write a program that prompts the user for a dish name and returns the price of that dish if it exists in the menu.
Task 6. Write a program that takes a list of strings as input and returns a dictionary where the keys are the unique characters in the strings and the values are the number of occurrences of that character in the strings.
Task 7. Create a dictionary that stores the names and birth years of 5 famous people. Write a program that prompts the user for a birth year, and then returns the names of the people born in that year if any exist in the dictionary.
Task 8. Write a program that takes a list of numbers as input and returns a dictionary where the keys are the numbers and the values are the running total of all the numbers up to that point in the list.