Table of Contents

4 [0] Dictionaries

Dictionaries are sets where each element (a key) has associated an object (a value). In fact, sets can be seen as dictionaries where the elments have not associations. As sets, dictionaries are efficient for indexing by keys.


In [ ]:
help({})

4.1 [0] Static definition of a dictionary


In [ ]:
a = {'Macinstosh':'OSX', 'PC':'Windows', 'Macintosh-Linux':'Linux', 'PC-Linux':'Linux'}
a

4.2 [0] Indexing of a dictionary by a key (O(1))


In [ ]:
a['PC']

4.3 [0] Testing if a key is the dictionary (O(1))


In [ ]:
'PC-Linux' in a

4.4 [1] Getting the keys (O(n))


In [ ]:
a.keys()

4.5 [1] Getting the values (O(n))


In [ ]:
a.values()

4.4 [1] Determining the position of a key in a dictionary (O(n))


In [ ]:
list(a.keys()).index("Macintosh-Linux")

In [ ]:
for i in a.keys():
    print(i)

4.6 [0] Inserting a new entry (O(1))


In [ ]:
a['Celullar'] = "Android"
a

[0] 4.7 Deleting an entry (O(1))


In [ ]:
del a['Celullar']
a

In [ ]:
# Modifiying an entry
a.update({"PC": "Windows 10"})
a

4.8 [1] Dictionaries are mutable


In [ ]:
id(a)

In [ ]:
a['Macintosh-Linux'] = 'Linux for the Mac'
a

In [ ]:
id(a)

4.9 [0] Looping a dictionary (O(n))


In [ ]:
for i in a:
    print(i, a[i])

In [ ]:
for i in a.values():
    print(i)

In [ ]:
for i in a.items():
    print(i)