Dictionaries & Sets

In [1]:
# How to initialize a dict
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
Out[1]:
True

Dict comprehension

In [2]:
DIAL_CODES = [
    (86, 'China'),
    (91, 'India'),
    (1, 'United States'),
    (62, 'Indonesia'),
    (55, 'Brazil'),
    (92, 'Pakistan'),
    (880, 'Bangladesh'),
    (234, 'Nigeria'),
    (7, 'Russia'),
    (81, 'Japan'),
]
country_code = {country: code for code, country in DIAL_CODES}
country_code
Out[2]:
{'China': 86,
 'India': 91,
 'United States': 1,
 'Indonesia': 62,
 'Brazil': 55,
 'Pakistan': 92,
 'Bangladesh': 880,
 'Nigeria': 234,
 'Russia': 7,
 'Japan': 81}
In [3]:
{code: country.upper() for country, code in country_code.items() if code < 66}
Out[3]:
{1: 'UNITED STATES', 62: 'INDONESIA', 55: 'BRAZIL', 7: 'RUSSIA'}

collections

In [6]:
import collections

ct = collections.Counter('abracadabra')
print(ct)
ct.update('aaaaazzz');
print(ct)
ct.most_common(2)
Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
Counter({'a': 10, 'z': 3, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
Out[6]:
[('a', 10), ('z', 3)]

Sets

Find occurrences

In [8]:
found = 0
for n in needles:
    if n in haystack:
        found += 1

The above does the same thing as the below. The above is faster than below but the below works on any iterables.

In [ ]:
found = len(set(needles) & set(haystack))
# another way:
found = len(set(needles).intersection(haystack))

Immutable sets

In [9]:
frozenset(range(10))
Out[9]:
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

Set Comprehension

In [10]:
{i for i in range(10)}
Out[10]:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
In [11]:

Out[11]:
True
In [ ]: