?print-pdf
' Created for
dictionary = {
'key1': value 1,
'key2': value 2,
'keyN': value N
}
collections
module.
# Example 1: Basic dictionary usage
en_bg_dict = {
'apple': 'ябълка',
'orange':'портокал',
'banana':'банан'
}
print(en_bg_dict['apple'])
# ябълка
### Example 2: Duplicate keys overwrite previous values
en_bg_dict = {
'apple': 'ябълка',
'orange':'портокал',
'banana':'банан',
'apple':'манго',
}
print(en_bg_dict['apple'])
# манго
item = dictionary_name[key]
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
apples_price = prices['apples']
print(f'{apples_price:.2f}')
# 2.50
oranges_price = prices['oranges']
print(f'{oranges_price:.2f}')
# 2.43
dictionary_name[key] = new_value
prices = {
'apples': 2.50,
'oranges': 2.43,
'bananas': 3.50
}
prices['apples'] = 2.20 # Change value for key 'apples'
print(prices)
# Output:
# {'apples': 2.2, 'oranges': 2.43, 'bananas': 3.5}
key
that does not already exist.
dictionary_name[new_key] = new_value
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
### Add new key-value pair:
prices['plums'] = 4.30
print(prices)
# {'apples': 2.5, 'oranges': 2.43, 'bananas': 3.5, 'plums': 4.3}
del
operatordel
operator removes the key-value pair associated with the given key from the dictionary.
del dictionary[key]
key
does not exist, a KeyError
will be raised.
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
# Delete '"oranges": 2.43' pair:
del prices['oranges']
print(prices)
# {'apples': 2.5, 'bananas': 3.5}
# Try to delete a non-existing key (uncomment to see the error):
# del prices['plums']
# KeyError: 'plums'
pop()
del
operator, pop()
removes the key-value pair and returns the value associated with the given key.
value = dictionary.pop(key[, default])
KeyError
will be raised.
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
# Remove 'apples' key-value pair and return its value
apples_price = prices.pop('apples')
print(apples_price)
# Output: 2.5
print(prices)
# Output: {'oranges': 2.43, 'bananas': 3.5}
# Try to remove 'plums' key-value pair from the dictionary. No KeyError raised, as default is provided
plums_price = prices.pop('plums', None)
print(plums_price)
# Output: None
print(prices)
# Output: {'oranges': 2.43, 'bananas': 3.5}
dict.keys()
dict.keys()
method returns a dict view object of dictionary keysdict_keys
object can be used in loops or converted into a list if needed.
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
# Get all the keys in the dictionary as dict_keys view
keys = prices.keys()
# Convert dict_keys view to a list to display all the keys
print(list(keys))
# Output: ['apples', 'oranges', 'bananas']
dict_keys
view object is dynamic!dict_keys
view.
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
# Get all the keys in the dictionary
keys = prices.keys()
print(keys)
# Output: dict_keys(['apples', 'oranges', 'bananas'])
# Modify the dictionary by adding a new key-value pair
prices["plums"] = 4.30
# The dict_keys view reflects the change automatically
print(keys)
# Output: dict_keys(['apples', 'oranges', 'bananas', 'plums'])
# Remove an item
del prices["apples"]
# The dict_keys view reflects the deletion as well
print(keys)
# Output: dict_keys(['oranges', 'bananas', 'plums'])
dict.values()
dict.values()
method of a dictionary returns a dict_values view object of dictionary valuesdict_values
object can be used in loops or converted into a list if needed.
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
# Get all the values in the dictionary as dict_values view
values = prices.values()
# Convert dict_values view to a list to display all the values
print(list(values))
# [2.5, 2.43, 3.5]
dict_values
view object is dynamic!
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
values = prices.values()
# Print initial values
print("Initial values:", list(values))
# Initial values: [2.5, 2.43, 3.5]
# Modify the dictionary by adding a new item
prices["plums"] = 4.30
# Print values after modification
print("Updated values:", list(values))
# Updated values: [2.5, 2.43, 3.5, 4.3]
dict.items()
dict.items()
method of a dictionary returns a dict view object of dictionary items, i.e. a view of key-value pairs
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
prices_items = prices.items()
print(prices_items)
# dict_items([('bananas', 3.5), ('apples', 2.5), ('oranges', 2.43)])
items()
- dynamic view example
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
# get prices items view:
prices_items = prices.items()
print("before:", prices_items)
# remove an item:
del prices["oranges"]
# check if prices_items reflects the change:
print("after:", prices_items)
before: dict_items([('apples', 2.5), ('oranges', 2.43), ('bananas', 3.5)])
after: dict_items([('apples', 2.5), ('bananas', 3.5)])
Note that when using for-in
loop, dict_name is the same as dict_name.keys()
### Variant 1:
for key in dict_name:
# do something with a key
# ### Variant 2:
for key in dict_name.keys():
# do something with a key
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
for key in prices:
print(key, end=",")
# apples,oranges,bananas,
for key in prices.keys():
print(key, end=",")
# apples,oranges,bananas,
for value in dict_name.values():
# do something with a value
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
for v in prices.values():
print(v)
2.43
3.5
2.5
for key, value in dict_name.items():
# do something with a key
# do something with a value
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
for fruit, price in prices.items():
print(f'{fruit}={price}')
# apples=2.5
# oranges=2.43
# bananas=3.5
dict
class @python docs
set = {value1, value2, valueN}
set_of_imutables = {"a", 1, "b", 2, 3}
print(set_of_imutables) #{'a', 'b', 2, 3, 1}
set_of_mutables = { [1,2,3], ["a", "b"] }
print(set_of_imutables) #TypeError: unhashable type: 'list'
int_dup_numbers = {1, 2, 3, 1, 2, 4, 3, 5, 1, 2, 3}
print(int_dup_numbers)
# {1, 2, 3, 4, 5, 6}
int_numbers = {1, 2, 3, 4, 5}
int_dup_numbers = {1, 2, 3, 1, 2, 4, 3, 5, 1, 2, 3}
print(int_numbers == int_dup_numbers)
# True
set()
# from l1 crate l2 with unique values:
l1 = [1,2,1,3,2,5,3]
l2 = list(set(l1))
print(l2)
# [1, 2, 3, 5]
key:value
pairs.
import time
# Creating a large set and list for demonstration
large_set = set(range(10_000_000))
large_list = list(range(10_000_000))
# Searching for an element in the set
start_time = time.time()
exists_in_set = 999999 in large_set # Searching for a high number
set_duration = time.time() - start_time
# Searching for the same element in the list
start_time = time.time()
exists_in_list = 999999 in large_list # Searching for the same high number
list_duration = time.time() - start_time
print(f"Time taken for search in set: {set_duration:.8f} seconds")
print(f"Time taken for search in list: {list_duration:.8f} seconds")
# Time taken for search in set: 0.00000381 seconds
# Time taken for search in list: 0.01182604 seconds
import time
# Creating a large set and list for demonstration
large_set = set(range(10_000_000))
large_list = list(range(10_000_000))
# Iterating through a list and a set
start_time = time.time()
for item in large_list:
pass # Simple iteration
list_iteration_duration = time.time() - start_time
start_time = time.time()
for item in large_set:
pass # Simple iteration
set_iteration_duration = time.time() - start_time
print(f"Time taken for iterating list: {list_iteration_duration:.8f} seconds")
print(f"Time taken for iterating set: {set_iteration_duration:.8f} seconds")
# Time taken for iterating list: 0.26020551 seconds
# Time taken for iterating set: 0.29316807 seconds
Returns new set, which elements are in either sets.
Pipe operator |
or method union
can be used
set1 = {1, 2, 3, 4}
set2 = {5, 4}
union1 = set1 | set2
union2 = set1.union(set2)
print(union1)
print(union2)
# {1, 2, 3, 4, 5}
# {1, 2, 3, 4, 5}
Returns new set, which elements belong to both sets.
Ampersand operator &
or method intersection
can be used
set1 = {1, 2, 3, 4}
set2 = {5, 4}
intersec1 = set1 & set2
intersec2 = set1.intersection(set2)
print(intersec1)
print(intersec2)
# {4}
# {4}
C = B-A, where C is a new set, which elements are the elements of B, which are not present in A
Operator -
or method difference
can be used
set1 = {1, 2, 3, 4, 5}
set2 = {5, 4}
dif1 = set1.difference(set2)
dif2 = set1 - set2
print(dif1)
print(dif2)
# {1, 2, 3}
# {1, 2, 3}
C = A △ B, where C is a new set, which elements are either in sets A or B but not in both.
Operator ^
or method symmetric_difference
can be used
set1 = {1, 2, 3, 4}
set2 = {5, 4}
sym_dif = set1.symmetric_difference(set2)
print(sym_dif)
# {1, 2, 3, 5}
task_best_students_scores.py
student_scores
data, create a new data structure named best_students_scores
, storing the information (name and score) only for students with scores greater than 4.00best_students_scores
as shown:
Ivan - 5.00
Maria - 5.50
Georgy - 5.00
task_min_max_student_score.py
Maria - 5.5
Alex - 3.5
numbers = [2.50, 2.43, 3.50]
# Get max value in list:
print( max(numbers) )
prices = {
"apples": 2.50,
"oranges": 2.43,
"bananas": 3.50
}
# Get max value in a dict
print( max(prices.values()) )
# Get the key of max value in a dict
print( max(prices, key=prices.get) )
task_simple_word_index.py
text = """apple and banana one apple one banana
a red apple and a green apple"""
# not nessesarly in the same order
apple - 4
and - 2
banana - 2
one - 2
a - 2
red - 1
green - 1
str.split()
method, as shown:
text = "some words delimited by spaces"
words_list = text.split()
print(words_list)
# ['some', 'words', 'delimited', 'by', 'spaces']
list.count(x)
method which return the number of times x appears in the list.
l = [1,1,1,2,2,2,2,3,3]
print(l.count(1)) # 3
print(l.count(2)) # 4
print(l.count(3)) # 2
job_candidate_skills.py
Matched Skills: Python, Git
Missing Skills: SQL, Django
Extra Skills: Flask, JavaScript
skills = {'Python', 'Git'}
print(f'Skills: {", ".join(skills)}')
These slides are based on
customised version of
framework