K. Dictionaries

Python dictionaries (dict) are efficient ways of storing information. Just as an actual dictionary stores a word and its corresponding definition, so a Python dict stores some key and a corresponding value. Using dictionaries can make your code more readable because a label is assigned to each value in the dictionary. Contrast this with list objects, which are unlabeled. Dictionaries are created by using a set of curly brackets, {}.

my_dict = {}
print(my_dict)

{}

print(type(my_dict))

<class 'dict'>

When we have a dict, we can add values to it by using square brackets, []. We put the key inside these square brackets. Usually, it is some string, but it can actually be any immutable type (e.g., a Python tuple, which is the immutable form of a Python list). Here we create two keys, fname and lname, for a first name and last name, respectively.

my_dict['fname'] = 'Daniel'
my_dict['lname'] = 'Chen'

We can also create a dictionary directly, with key–value pairs instead of adding them one at a time. To do this, we use our curly brackets, with the key–value pairs being specified by a colon.

my_dict = {'fname': 'Daniel', 'lname': 'Chen'}
print(my_dict)

{'fname': 'Daniel', 'lname': 'Chen'}

To get the values from our keys, we can use the square brackets with the key inside.

fn = my_dict['fname']
print(fn)

Daniel

We can also use the get method.

ln = my_dict.get('lname')
print(ln)

Chen

The main difference between these two ways of getting the values from the dictionary is the behavior that occurs when you try to get a nonexistent key. When using the square brackets notation, trying to get a key that does not exist will return an error.

# will return an error
print(my_dict['age'])

Traceback (most recent call last):
  File "<ipython-input-1-404b91316179>", line 2, in <module>
    print(my_dict['age'])
KeyError: 'age'

In contrast, the get method will return None.

# will return None
print(my_dict.get('age'))

None

To get all the keys from the dict, we can use the keys method.

# get all the keys in the dictionary
print(my_dict.keys())

dict_keys(['fname', 'lname'])

To get all the values from the dict, we can use the values method.

# get all the values in the dictionary
print(my_dict.values())

dict_values(['Daniel', 'Chen'])

To get every key–value pair, you can use the items method. This can be useful if you need to loop through a dictionary.

print(my_dict.items())

dict_items([('fname', 'Daniel'), ('lname', 'Chen')])

Each key–value pair is returned in a form of a tuple, as indicated by the use of round brackets, ().

More on dictionaries can be found in the official documentation on data structures.1

1. https://docs.python.org/3/tutorial/datastructures.html#dictionaries

..................Content has been hidden....................

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