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.

Dictionary is mutable, iterated, unordered but indexable by the keys data structure. 

Dictionary keys can only be immutable data types. In Python, these are numbers, strings, 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 dictionary,
'белый', 'красный', 'зеленый', 'синий', 'черный'  - their values.


Empty dictionary.

Two ways for creating 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 this word')
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 Describtion

d.get(key)
d.get(key, other value)

ascii = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
value = ascii_code.get('B')
print(value) # output 66

value = ascii.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()

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

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

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

Can check value in d.values()

d.items() ascii_code = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
for key, value in ascii_code.items():
    print(key, value)
# Output:
# A 65
# B 66
# C 67
# D 68
Method items() allows getting all pairs keys and values of a dictionary

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 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, by values, by elements?

Exercises:


Tasks:


Extra:



 

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