Zbiory i słowniki / Sets and dictionaries

Dokumentacja Pythona / Python documentation:
https://docs.python.org/3/tutorial/datastructures.html#sets
https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Zbiory / Sets

Elementami zbiorów są dowolne, niezmienialne (ściślej: hashowalne) obiekty.
The elements of a set can be arbitrary, immutable (more precisely, hashable) objects.

Konstrukcja zbioru przez podanie jego elementów / set construction by writing down its elements:

In [1]:
s = {1, 4, 5, 7, 8, "a", "b"}

Dodanie 1 - zbiór pozostaje bez zmian / Adding 1 - the set is unchanged:

In [2]:
s.add(1)
print(s)
{1, 'b', 4, 5, 7, 8, 'a'}

Usunięcie elementu 4 / Deletion of the element 4:

In [3]:
s.remove(4)
print(s)
{1, 'b', 5, 7, 8, 'a'}

Konstrukcja zbioru z obiektu iterowalnego (np. napisu):
Set construction from an iterable (e.g. string):

In [4]:
s = set("lokomotywa")
t = set("abcaca")
print(s, t)
{'k', 'm', 'l', 'w', 'a', 't', 'o', 'y'} {'c', 'a', 'b'}

Operacje mnogościowe:
Set-theoretic operations:

In [5]:
print(s | t)  # Suma / union
print(s & t)  # Przekrój / intersection
print(s - t)  # Różnica / difference
print(s ^ t)  # Różnica symetryczna / symmetric difference
print(s ^ t == (s - t) | (t - s))  # Porównanie / Comparison
print('l' in s)  # Operator należenia / Membership operator
{'c', 'b', 'k', 'm', 'l', 'w', 'a', 't', 'o', 'y'}
{'a'}
{'k', 'l', 'w', 'o', 't', 'm', 'y'}
{'c', 'b', 'k', 'l', 'w', 'o', 't', 'm', 'y'}
True
True

Inne operacje są na slajdach z wykładu.
See lecture slides for additional operations.

Konstrukcja przez schemat (zbiór składany):
Construction by set comprehension:

In [6]:
{n**2 for n in range(5)}
Out[6]:
{0, 1, 4, 9, 16}

Zbiór pusty - nie {}! / Empty set - not {}!

In [7]:
set()  # Zbiór pusty / Empty set
Out[7]:
set()

Niezmienialny odpowiednik - frozenset:
Immutable equivalent - frozenset:

In [8]:
s = frozenset([1, 2, 3])
# s.add(4)  # Nielegalne / Illegal
s |= {4}  # Ok (równoważne s = s | {4}) / Ok (equivalent to s = s | {4})
print(s)
frozenset({1, 2, 3, 4})

Słowniki / Dictionaries

Słowniki stowarzyszają klucze z wartościami. Klucze stanowią zbiór (nie powtarzają się, muszą być hashowalne).
Dictionaries associate keys and values. Keys in a dictionary form a set (they are unique and must be hashable).

Konstrukcja przez pary klucz: wartość:
Construction with pairs key: value:

In [9]:
d = {1 : 'a', 2 : 'b', 'abc' : [1,2,3], (1,2) : 1}

Odczytanie wartości / Reading a value:

In [10]:
print(d[1])
print(d[(1,2)])
a
1

Nowa wartość lub zmiana starej / New value or changing of existing one:

In [11]:
d[1] = 1000
d['abc'] = 'def'
print(d)
{1: 1000, 2: 'b', 'abc': 'def', (1, 2): 1}

Usunięcie klucza (i stowarzyszonej z nim wartości) / Deletion of a key (and the associated value):

In [12]:
del d[1]
print(d)
{2: 'b', 'abc': 'def', (1, 2): 1}

Iteracja po kluczach / Iteration over keys:

In [13]:
for k in d:  # = for k in d.keys()
    print(k)
2
abc
(1, 2)

Iteracja po wartościach / Iteration over values:

In [14]:
for v in d.values():
    print(v)
b
def
1

Iteracja po parach klucz-wartość / Iteration over key-value pairs:

In [15]:
for k, v in d.items():
    print(k, v)
2 b
abc def
(1, 2) 1

Schemat konstrukcji słowników / Dictionary comprehension:

In [16]:
{n: n ** 2 for n in range(5)}
Out[16]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

"Bijektywny" słownik i jego odwrotność:
a "bijective" dictionary and its inverse:

In [17]:
d1 = {1 : 'a', 2 : 'b', 3 : 'c'} 
d2 = {v : k for k, v in d1.items()} 
print(d1, d2)
{1: 'a', 2: 'b', 3: 'c'} {'a': 1, 'b': 2, 'c': 3}

Pusty słownik / Empty dictionary:

In [18]:
{}
Out[18]:
{}

Konstrukcja słownika z ciągu par klucz-wartość:
Construction of a dictionary from a sequence of key-value pairs:

In [19]:
dict([(1,2), (2,3), "AB"])
Out[19]:
{1: 2, 2: 3, 'A': 'B'}

Konstrukcja słownika przez parametry nazwane:
Construction of a dictionary by named parameters:

In [20]:
dict(k1='a', k2='b')
Out[20]:
{'k1': 'a', 'k2': 'b'}

Sprawdzenie, czy klucz jest w słowniku:
Checking whether a dictionary contains a key:

In [21]:
print(1 in d1)
print('b' in d2)
print('x' in d2)
True
True
False