Python. Dictionaries (en)

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.

my_dict = {'key1' : 'value1', 'key2' : 'value2', ...}

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': 'черный'}

'white', 'red', 'green', 'blue', 'black' - keys of the dictionary,
'белый', 'красный', 'зеленый', 'синий', 'черный'  - their values.


Empty dictionary.

Two ways to create empty dictionaries:

d = dict()
d = {}


Access to the value of an element by key.

colors = {'white': 'белый', 'red': 'красный', 'green': 'зеленый', 'blue': 'синий', 'black': 'черный'}
print(colors['red']) # output красный
print(colors['blue']) # output синий
print(colors['yellow']) # KeyError: 'yellow'


An important feature of the dictionary is its dynamism.

Changing an element

colors = {'green': 'зиленый', 'blue': 'синий', 'black': 'черный'}
colors['green'] = 'зеленый' # change value with key 'green'
print(colors) # {'green': 'зеленый', 'blue': 'синий', 'black': 'черный'}

Adding an element

colors = {'blue': 'синий', 'black': 'черный'}
colors['yellow'] = 'желтый' # add new element
print(colors) # {'blue': 'синий', 'black': 'черный', 'yellow': 'желтый'}

Delete element

 

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.
d.keys()

d = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
letters = list(d.keys())
print(letters)  # ['A', 'B', 'C', 'D']

Method keys() allows getting a list of all the keys of a dictionary
d.values() d = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
letters = list(d.values())
print(letters)  # [65, 66, 67, 68]

Method values() allow getting a list of all the values of a dictionary

Can check the value in d.values()

d.items() d = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
for key, value in d.items():
    print(key, value)
# Output:
# A 65
# B 66
# C 67
# D 68
Method items() allow getting all pairs of keys and values of a dictionary
d1.update(d2) d1 = {'A': 65, 'B': 66}
d2 = {'C': 67, 'D': 68}
d1.update(d2)
print(d1) # {'A': 65, 'B': 66, 'C': 67, 'D': 68}
Merge two dictionaries into one

Iteration dictionary

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}


Several ready dictionaries for solving tasks:

Morse code
  • {"A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--.."}
ASCII code
  • {i: chr(i) for i in range(128)}
Dictionary of Australian Open men's singles champions 
  • {1969: 'Rod Laver', 1970: 'Arthur Ashe', 1971: 'Ken Rosewall', 1972: 'Ken Rosewall', 1973: 'John Newcombe', 1974: 'Jimmy Connors', 1975: 'John Newcombe', 1976: 'Mark Edmondson', 1977: 'Roscoe Tanner and Vitas Gerulaitis', 1978: 'Guillermo Vilas', 1979: 'Guillermo Vilas', 1980: 'Brian Teacher', 1981: 'Johan Kriek', 1982: 'Johan Kriek', 1983: 'Mats Wilander', 1984: 'Mats Wilander', 1985: 'Stefan Edberg', 1987: 'Stefan Edberg', 1988: 'Mats Wilander', 1989: 'Ivan Lendl', 1990: 'Ivan Lendl', 1991: 'Boris Becker', 1992: 'Jim Courier', 1993: 'Jim Courier', 1994: 'Pete Sampras', 1995: 'Andre Agassi', 1996: 'Boris Becker', 1997: 'Pete Sampras', 1998: 'Petr Korda', 1999: 'Yevgeny Kafelnikov', 2000: 'Andre Agassi', 2001: 'Andre Agassi', 2002: 'Thomas Johansson', 2003: 'Andre Agassi', 2004: 'Roger Federer', 2005: 'Marat Safin', 2006: 'Roger Federer', 2007: 'Roger Federer', 2008: 'Novak Djokovic', 2009: 'Rafael Nadal', 2010: 'Roger Federer', 2011: 'Novak Djokovic', 2012: 'Novak Djokovic', 2013: 'Novak Djokovic', 2014: 'Stan Wawrinka', 2015: 'Novak Djokovic', 2016: 'Novak Djokovic', 2017: 'Roger Federer', 2018: 'Roger Federer', 2019: 'Novak Djokovic', 2020: 'Novak Djokovic', 2021: 'Novak Djokovic', 2022: 'Rafael Nadal'}

 


Questions:

  1. Name four features of a data structure Dictionary.
  2. Explain cases when we can use Dictionaries. Give two examples.
  3. What does each element of the dictionary consist of?
  4. 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.

 

Категория: Programming languages | Добавил: bzfar77 (30.01.2022)
Просмотров: 4847 | Теги: data structure, Dictionary, Python, key, Value | Рейтинг: 4.3/6
Всего комментариев: 0
avatar