4. dict

  • dict are key-value storage

  • Mutable - can add, remove, and modify items

4.1. Initializing

4.1.1. Initialize empty

my_dict = {}
my_dict = dict()

4.1.2. Initialize with many elements

  • Comma after last element is optional

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski'
}
my_dict = dict(
    first_name='Jan',
    last_name='Twardowski'
)

4.1.3. Duplicating items are overridden by latter

my_dict = {
    'name': 'Twardowski',
    'name': 'Иванович',
}
# {'name': 'Иванович'}

4.1.4. Key can be any hashable object

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}
my_dict = {
    1961: 'First Human Space Flight',
    1969: 'First Step on the Moon',
}
my_dict = {
    (1,): 'tuple with one element',
    (2, 3, 4): 'tuple with many elements',
}
key = 'last_name'

my_dict = {
    'fist_name': 'key can be str',
    1: 'key can be int',
    1.5: 'key can be float',
    (1,): 'key can be tuple',
    (2, 3, 4): 'key can be tuple',
    key: 'key can be str',
}

4.1.5. Value can be any object

my_dict = {
    'date': '1969-07-21',
    'age': 42,
    'astronaut': {'name': 'Jan Twardowski', 'medals': {'Medal of Honor', 'Purple Heart'}},
    'agency': ['POLSA', 'Roscosmos', 'ESA'],
    'location': ('Baikonur', 'Johnson Space Center'),
}

4.1.6. Order of dict elements

  • Since Python 3.7 dict keeps order of elements

  • Before Python 3.7 dict order is not ensured!!

Note

Since Python 3.7: The insertion-order preservation nature of dict objects is now an official part of the Python language spec.

4.2. Adding elements

  • Adds if value not exist

  • Updates if value exist

4.2.1. Adding using [...] syntax

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict['agency'] = 'POLSA'

print(my_dict)
# {
#   'first_name': 'Jan',
#   'last_name': 'Twardowski',
#   'agency': 'POLSA'
# }

4.2.2. Adding using .update() method

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict.update(agency='POLSA')
# {
#   'first_name': 'Jan',
#   'last_name': 'Twardowski',
#   'agency': 'POLSA'
# }
my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict.update(agency=['POLSA', 'ESA', 'Roscosmos'])
# {
#   'first_name': 'Jan',
#   'last_name': 'Twardowski',
#   'agency': ['POLSA', 'ESA', 'Roscosmos']
# }
my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict.update({'agency': 'POLSA'})
# {
#   'first_name': 'Jan',
#   'last_name': 'Twardowski',
#   'agency': 'POLSA'
# }

4.3. Removing items

4.3.1. .pop()

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
    'agency': 'POLSA',
}

value = my_dict.pop('agency')

my_dict  # {'first_name', 'Jan', 'last_name': 'Twardowski'}
value    # 'POLSA'

4.3.2. del keyword

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
    'agency': 'POLSA',
}

del my_dict['agency']

my_dict
# {'first_name': 'Jan', 'last_name': 'Twardowski'}

4.4. Accessing elements

4.4.1. Check if value in dict

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

'first_name' in my_dict
# True

'agency' in my_dict
# False

4.4.2. Accessing values with [...]

  • [...] throws KeyError exception if key not found in dict

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict['last_name']
# Twardowski
my_dict = {
    1961: 'First Human Space Flight',
    1969: 'First Step on the Moon',
}

my_dict[1961]
# 'First Human Space Flight'
my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict['agency']
# KeyError: 'agency'

4.4.3. Accessing values with .get(...)

  • .get(...) returns None if key not found

  • .get(...) can have default value, if key not found

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict.get('last_name')
# Twardowski
my_dict = {
    1961: 'First Human Space Flight',
    1969: 'First Step on the Moon',
}

my_dict.get(1961)
# 'First Human Space Flight'
my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
}

my_dict.get('agency')
# None

my_dict.get('agency', 'n/a')
# 'n/a'

4.4.4. Accessing dict keys, values and key-value pairs

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
    'age': 42,
}

my_dict.keys()
# ['first_name', 'last_name', 'age']

my_dict.values()
# ['Jan', 'Twardowski', 42]

my_dict.items()
# [
#   ('first_name', 'Jan'),
#   ('last_name', 'Twardowski'),
#   ('age', 42)
# ]

4.5. Create dict from two sequences

  • zip is a generator

  • zip will create a list of pairs (like dict.items())

keys =  ['Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species']
values = [5.8, 2.7, 5.1, 1.9, 'virginica']

my_dict = dict(zip(keys, values))

print(my_dict)
# {
#   'Sepal length': 5.8,
#   'Sepal width': 2.7,
#   'Petal length': 5.1,
#   'Petal width': 1.9,
#   'Species': 'virginica'
# }

4.6. Length of a dict

my_dict = {
    'first_name': 'Jan',
    'last_name': 'Twardowski',
    'age': 42,
}

len(my_dict)
# 3

len(my_dict.keys())
# 3

len(my_dict.values())
# 3

len(my_dict.items())
# 3

4.7. Assignments

4.7.1. Aviation Language

  • Complexity level: easy

  • Lines of code to write: 3 lines

  • Estimated time of completion: 10 min

  • Filename: solution/dict_alphabet.py

English
  1. Create translator to pilot's alphabet

  2. Each letter has it's phonetic counterpart

  3. To convert table use multiline select with alt key in your IDE

  4. Ask user to input letter

  5. User will always put only one capitalized letter or number

  6. Print phonetic letter pronunciation

  7. If user type character not existing in alphabet, print: "Pilots don't say that"

  8. Do not use if, try, and except

Polish
  1. Stwórz tłumacza do alfabetu pilotów

  2. Pojedynczym literom przyporządkuj ich fonetyczne odpowiedniki

  3. Do przekonwertowania tabelki wykorzystaj zaznaczanie wielu linijek za pomocą klawisza alt w Twoim IDE

  4. Zapytaj użytkownika o wprowadzenie litery

  5. Użytkownik zawsze poda tylko jedną dużą literę lub cyfrę

  6. Wypisz nazwę fonetyczną wymowę litery

  7. Jeżeli wpisał znak, który nie jest w alfabecie, wypisz: "Pilots don't say that"

  8. Nie używaj if, try ani except

Input
Letter, Pronounce
A, Alfa
B, Bravo
C, Charlie
D, Delta
E, Echo
F, Foxtrot
G, Golf
H, Hotel
I, India
J, Juliet
K, Kilo
L, Lima
M, Mike
N, November
O, Oscar
P, Papa
Q, Quebec
R, Romeo
S, Sierra
T, Tango
U, Uniform
V, Victor
W, Whisky
X, X-Ray
Y, Yankee
Z, Zulu
The whys and wherefores
  • Defining dict with values

  • Type casting