One of a kind…

Built-ins

Creating a dictionary

>>> %%time
>>> dictionary = {'apricots': 4.5,
>>> 'blueberries': 12,
>>> 'cucumbers': 1.2,
>>> 'dates': 6.5
>>> }
>>> print(dictionary)
CPU times: user 4 µs, sys: 1 µs, total: 5 µs
Wall time: 7.87 µs
{'apricots': 4.5, 'blueberries': 12, 'cucumbers': 1.2, 'dates': 6.5}
>>> %%time
>>> dictionary = dict([('apricots', 4.5),
>>> ('blueberries', 12),
>>> ('cucumbers', 1.2),
>>> ('dates', 6.5)]
>>> )
>>> print(dictionary)
CPU times: user 7 µs, sys: 1 µs, total: 8 µs
Wall time: 10.5 µs
{'apricots': 4.5, 'blueberries': 12, 'cucumbers': 1.2, 'dates': 6.5}
>>> d = {(1,2): 'tuples',
>>> (1,3): 'can',
>>> (1,4): 'be',
>>> (1,5): 'keys'
>>> }
>>> print(d)

{(1, 2): 'tuples', (1, 3): 'can', (1, 4): 'be', (1, 5): 'keys'}
>>> d = {['lists', "can't", 'be', 'dictionary', 'keys']: 'Oopsie!'}

--------------------------------------------------------------------
TypeError Traceback (most recent call last)

<ipython-input-3-781cb5459fc7> in <module>
6 print(d)
7
----> 8 d = {['lists', "can't", 'be', 'dictionary', 'keys']: 'Oopsie!'}

TypeError: unhashable type: 'list'

Access dictionary value

>>> dictionary['apricots']4.5

Add value to dictionary (or update)

# Update values
>>> dictionary['apricots'] = 4.7
# Add values
>>> dictionary['elderberries'] = 14
# or
>>> dictionary.update([('feijoa', 6)])
{'apricots': 4.7,
'blueberries': 12,
'cucumbers': 1.2,
'dates': 6.5,
'elderberries': 14,
'feijoa': 6}
>>> dictionary['Granadilla']--------------------------------------------------------------------
KeyError Traceback (most recent call last)

<ipython-input-31-87ef655b7951> in <module>
----> 1 dictionary['Granadilla']

KeyError: 'Granadilla'
>>> document = "The quick brown fox jumps over the lazy dog">>> counter = {}
>>> for word in document.lower().split():
>>> counter[word] = counter.get(word, 0) + 1
{'the': 2,
'quick': 1,
'brown': 1,
'fox': 1,
'jumps': 1,
'over': 1,
'lazy': 1,
'dog': 1}

Remove a value from a dictionary

>>> del dictionary['elderberries']{'apricots': 4.7,
'blueberries': 12,
'cucumbers': 1.2,
'dates': 6.5,
'feijoa': 6}
>>> dictionary.pop('cucumbers'){'apricots': 4.7, 'blueberries': 12, 'dates': 6.5, 'feijoa': 6}
>>> dictionary.clear(){}>>> dictionary = {'apricots': 4.5, 
'blueberries': 12,
'cucumbers': 1.2,
'dates': 6.5
}

Length of a dictionary

>>> len(dictionary)4

Membership and dictionary

>>> 'dates' in dictionaryTrue>>> 'apples' not in dictionaryTrue>>> 12 in dictionary
# (12 is the price of blueberries)
False

View objects

>>> dictionary.items()dict_items([('apricots', 4.5), ('blueberries', 12), ('cucumbers', 1.2), ('dates', 6.5)])>>> dictionary.keys()dict_keys(['apricots', 'blueberries', 'cucumbers', 'dates'])>>> dictionary.values()dict_values([4.5, 12, 1.2, 6.5])Iteration on view object
>>> for key, value in dictionary.items():
>>> print(key+ ':', value)
apricots: 4.5
blueberries: 12
cucumbers: 1.2
dates: 6.5
>>> for key, value in dictionary:
>>> print(key+ ':', value)
--------------------------------------------------------------------
ValueError Traceback (most recent call last)

<ipython-input-34-42e38a312a9d> in <module>
----> 1 for key, value in dictionary:
2 print(key+ ':', value)

ValueError: too many values to unpack (expected 2)

Zip it… not!

>>> zipp = zip(['apricots', 'blueberries', 'cucumbers', 'dates'],
[4.5, 12, 1.2, 6.5]
)
>>> print(zipp)
<zip object at 0x7fac20077040>>>> print(zipp['apricots'])--------------------------------------------------------------------
TypeError Traceback (most recent call last)

<ipython-input-21-e32100618c12> in <module>
3 )
4 print(zipp)
----> 5 print(zipp['apricots'])

TypeError: 'zip' object is not subscriptable
>>> list(zip((1, 2, 3, 4),('a', 'b', 'c', 'd'), (True, False, True, False)))[(1, 'a', True), (2, 'b', False), (3, 'c', True), (4, 'd', False)]>>> for k, v in zip(['apricots', 'blueberries', 'cucumbers', 'dates'], [4.5, 12, 1.2, 6.5]):
>>> print(k +':', v)
apricots: 4.5
blueberries: 12
cucumbers: 1.2
dates: 6.5

Dictionary comprehension

>>> %%time
>>> powers = {n: n**2 for n in range(10)}
CPU times: user 20 µs, sys: 0 ns, total: 20 µs
Wall time: 21.9 µs

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> %%time
>>> powers = {}
>>> for n in range(10):
>>> powers[n] = n **2
CPU times: user 107 µs, sys: 0 ns, total: 107 µs
Wall time: 121 µs

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> odd_powers = {n: n**2 for n in range(10) if n%2==0}{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Replacing lambda

>>> temperatures_f = {'t1': -40, 't2': -20, 't3': -10, 't4': 0, 't5': 10, 't6': 100}>>> %%time
>>> celsius = list(map(lambda x:(x-32)/1.8, temperatures_f.values()))
>>> temperatures_c = dict(zip(temperatures_f.keys(), celsius))
CPU times: user 25 µs, sys: 0 ns, total: 25 µs
Wall time: 28.1 µs

{'t1': -40.0,
't2': -28.88888888888889,
't3': -23.333333333333332,
't4': -17.77777777777778,
't5': -12.222222222222221,
't6': 37.77777777777778}
>>> %%time
>>> temperatures_c = {k:(v-32)/1.8 for (k,v) in temperatures_f.items()}
CPU times: user 15 µs, sys: 2 µs, total: 17 µs
Wall time: 20.3 µs

{'t1': -40.0,
't2': -28.88888888888889,
't3': -23.333333333333332,
't4': -17.77777777777778,
't5': -12.222222222222221,
't6': 37.77777777777778}

Conclusion

Data Scientist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store