Dictionaries

Dictionaries are a different type of structure. Instead of being ordered arrays, they are key-value storage types. Dictionaries do not have any order, per se. Instead, they store everything as key-value pairs. As physical keys, the dictionary's keys have to be unique and unambiguously static. In other words, immutable. Hence, there cannot be two keys of the same value, and lists cannot be used as keys, but tuples can. Frequently, however, keys are strings, as they allow us to add some sort of semantics to the structure:

person = {'name': 'Jim',
'surname': 'Hawkins',
'age':17
}

As you can see, dictionaries are defined by the curly brackets, with key-value pairs separated by the colon and split by the comma. Once the dictionary is assigned, you can retrieve values by using square brackets. This is the same as for lists and tuples, but it uses keys instead of indices:

>>> person['age']
17

Note that dictionaries do not support slicing. You can't push two keys at once, or reverse dictionary, as there is no order to start with.

Similarly, you can add key-value pairs to the dictionary, like this:

person['hair'] = 'red'

As there cannot be two keys of the same value, another assignment will override the previous value with no warnings:

person['hair'] = 'ginger'

As with lists, you can merge two dictionaries. One way to do that is through the .update method:

additional_info = {
'gender': 'male',
'nationality': 'british',
'age': 16
}

person.update(additional_info)

Similar to lists, dictionaries have a .pop() method. But in this case, the .pop() method requires a specific key, for which the value will be retrieved and removed:

>>> person.pop('age')
16

On top of the preceding methods, dictionaries have a couple of handy methods up their sleeve. First, you can get either keys or values as list-like structures by using .keys() or .values(), respectively. Sometimes, it is convenient to get iterables of key-value pairs. This can be achieved by using the .items() method:

>>> print({'name':'Jim', 'surname': 'Hawkins'}.items())
dict_items([('name', 'Jim'), ('surname', 'Hawkins')])

When you try to get values by submitting a key that is not in the dictionary, KeyError is raised. In cases where you don't want this behavior, use the .get() method. It takes two values: the first value is for the key and the second value is for the default value. The default value is one that .get() will return if there is no data in the dictionary:

>>> person.get('eye color', 'brown')
'brown'

Lastly, dictionaries can behave as iterables, as you can loop through them (more on that in Chapter 5, Loops and Other Compound Statements) or check whether an element is in them. However, both of these cases work with keys, but not values:

>>> 'name' in person
True

>>> 'Jim' in person
False
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.12.230