Dictionaries

Dictionaries are objects that represent unordered collections, where pairs of data objects are stored in pairs of key and value. Keys must be immutable objects, while values can be of any data type, including sets and lists. Dictionaries allow us to obtain data values based on keys.
Dictionaries can be created by assignment using { }, inside of which we define pairs as key : value. Pairs are separated with “,” . If multiple values are stated for the same key, only the last value is stored.
We can also create a dictionary with the command (constructor) dict(), where values are assigned to keys (see the example). Only one value can be assigned to each key, in contrast to the previous way of creating a dictionary.
An empty dictionary can be created either by leaving empty space inside { } or by typing dict().
>>> car = {'brand': 'BMW', 'model': 'X6', 'color': 'blue', 'color' : 'black'}
>>> print(car)
{'brand': 'BMW', 'model': 'X6', 'color': 'black'}

>>> pokemon = dict(species = 'Dragonite', attack = 263, defense = 198, HP = 209)
>>> print(pokemon)
{'species': 'Dragonite', 'attack': 263, 'defense': 198, 'HP': 209}

Accessing elements

Although unordered, elements of a dictionary can be accessed with their key, stating dictionary[key]. Accessing the dictionary’s elements by index will signal an error. Accessing with a non-existing key will signal an error. However, we can create a new key and assign a value to it.

>>> dict = {'A' : 10, 'B' : 9, 'C' : 8}
>>> print(dict['A']) #accessing the value of key 'A'
10

>>> print(dict['D']) #accessing a non-existing key 'D'
KeyError: 'D'

>>> dict['D'] = 7 #creating a new key 'D' and assigning a value to it
>>> print(dict)
{'A': 10, 'B': 9, 'C': 8, 'D': 7}

Iteration and membership

We can iterate through a dictionary using a for-loop. Membership to the dictionary can be tested with the membership operators in or not in, which return True if a key belongs to the dictionary, otherwise they return False. It’s important to state that the iterator through the dictionary represents the key of the pair on that position, not the value.

>>> player = {'first name' : 'Stephen', 'last name' : 'Curry', 'age' : 34, 'position' : 'point guard'}
>>> for i in player:
            print(i)
 
first name
last name
age
position

Some attribute commands for working with dictionaries

This is a list of some useful (attribute) commands which help can make your job while working with dictionaries a lot easier:
d.clear() – deletes all the elements from the dictionary
d.copy() – creates a shallow copy of the dictionary
>>> d = {'A': 0, 'M': 3, 'D': 7}
>>> g = d.copy()
>>> d.clear()
>>> print(d, g)
d.items() – returns a view of all the elements in the dictionary in the form of pairs (key, value)
d.keys() – returns a view of all the keys in the dictionary
d.values() – returns a view of all the values in the dictionary
>>> A = {'b' : 0, 'c' : 2, 'd' : -3, 'e' : 4}

>>> print(dict.items(), dict.keys(), dict.values())
dict_items([('b', 0), ('c', 2), ('d', -3), ('e', 4)]) dict_keys(['b', 'c', 'd', 'e']) dict_values([0, 2, -3, 4])
d.fromkeys(seq, val) – creates a new dictionary with keys from sequence seq and assigns value val to each key; if val is not specified, assigns None
d.get(key, val) – returns the value of the key key; if key doesn’t exist, returns the value val; If val is not specified, returns None
d.pop(key, val) – deletes the element with the key key and returns its value. If key is not found, returns val. If val is not stated, returns None
d.setdefault(key, val) – returns the value of the key key if it exists, otherwise adds that key to the dictionary, assigns the value val to it and returns that value
>>> keys = ['x', 'y', 'z']
>>> print(A.fromkeys(keys, 1))
{'x': 1, 'y': 1, 'z': 1}

>>> A.get('w',4)
4

>>> A.pop('x')
1
>>> print(A)
{'y': 1, 'z': 1}

>>> A.setdefault('w',2)
2
>>> print(A)
{'y': 1, 'z': 1, 'w': 2}
d.popitem() – deletes a random element from the dictionary and returns it in form of the pair (key, value). If the dictionary is empty, the program signals an error
d.update([pair]) – adds a new key-value pair from pair to the dictionary; if the key already exists, assigns the new value from pair to that key
>>> A.popitem()
('w', 2)
>>> print(A)
{'y': 1, 'z': 1}

>>> A.update({'m': 6})
>>> print(A)
{'y': 1, 'z': 1, 'm': 6}
len(d) – returns the number of elements (key-value pairs) in the dictionary d
sorted(d) – returns a list of sorted keys from the dictionary d
>>> dict = {'P': 1, 'Y': 4, 'T': 7, 'H': 2, 'O': 3, 'N': 5}

>>> print(len(dict))
6
>>> print(sorted(dict))
['H', 'N', 'O', 'P', 'T', 'Y']

Table of contents

Leave a Reply