Tuesday, March 31, 2020

Mike Driscoll: Python 101 – Learning About Dictionaries

Dictionaries are another fundamental data type in Python. A dictionary is a key, value pair. Some programming languages refer to them as hash tables. They are described as a mapping object that maps hashable values to arbitrary objects.

A dictionary’s keys must be immutable, that is, unable to change. Starting in Python 3.7, dictionaries are ordered. What that means is that when you add a new key, value pair to a dictionary, it remembers what order they were added. Prior to Python 3.7, this was not the case and you could not rely on insertion order.

You will learn how to do the following in this chapter:

  • Create dictionaries
  • Access dictionaries
  • Dictionary methods
  • Modifying dictionaries
  • Deleting from your dictionary

Let’s start off by learning about creating dictionaries!

You can create a dictionary in a couple of different ways. The most common method is by placing a comma-separated list key: value pairs within curly braces.

Let’s look at an example:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict
{'email': 'jdoe@gmail.com', 'first_name': 'James', 'last_name': 'Doe'}

You can also use Python’s built-in dict() function to create a dictionary. dict() will accept a series of keyword arguments (i.e. 1=’one’, 2=’two’, etc), a list of tuples or another dictionary.

Here are a couple of examples:

>>> numbers = dict(one=1, two=2, three=3)
>>> numbers
{'one': 1, 'three': 3, 'two': 2}
>>> info_list = [('first_name', 'James'), ('last_name', 'Doe'), ('email', 'jdoes@gmail.com')]
>>> info_dict = dict(info_list)
>>> info_dict
{'email': 'jdoes@gmail.com', 'first_name': 'James', 'last_name': 'Doe'}

The first example uses dict() on a series of keyword arguments. You will learn more about these when you learn about functions. You can think of keyword arguments as a series of keywords with the equals sign between them and their value.

The second example shows you how to create a list that has 3 tuples inside of it. Then you pass that list to dict() to convert it to a dictionary.

Accessing Dictionaries

Dictionaries claim to fame is that they are very fast. You can access any value in a dictionary via the key. If the key is not found, you will receive a KeyError.

Let’s take a look at how to use a dictionary:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict['first_name']
'James'

To get the value of first_name, you must use the following syntax: dictionary_name[key]

Now let’s try to get a key that doesn’t exist:

>>> sample_dict['address']
Traceback (most recent call last):
   Python Shell, prompt 118, line 1
builtins.KeyError: 'address'

Well that didn’t work! You asked the dictionary to give you a value that wasn’t in the dictionary!

You can use Python’s in keyword to ask if a key is in the dictionary:

>>> 'address' in sample_dict
False
>>> 'first_name' in sample_dict
True

You can also check to see if a key is not in a dictionary by using Python’s not keyword:

>>> 'first_name' not in sample_dict
False
>>> 'address' not in sample_dict
True

Another way to access keys in dictionaries is by using one of the dictionary methods. Let’s find out more about dictionary methods now!

Dictionary Methods

As with most Python data types, dictionaries have special methods you can use. Let’s check out some of the dictionary’s methods!

d.get(key[, default])

You can use the get() method to get a value. get() requires you to specify a key to look for. It optionally allows you to return a default if the key is not found. The default is None. Let’s take a look:

>>> print(sample_dict.get('address'))
None
>>> print(sample_dict.get('address', 'Not Found'))
Not Found

The first example shows you what happens when you try to get() a key that doesn’t exist without setting get‘s default. In that case, it returns None. Then the second example shows you how to set the default to the string “Not Found”.

d.clear()

The clear() method can be used to remove all the items from the dictionary.

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict
{'email': 'jdoe@gmail.com', 'first_name': 'James', 'last_name': 'Doe'}
>>> sample_dict.clear()
>>> sample_dict
{}

d.copy()

If you need to create a shallow copy of the dictionary, then the copy() method is for you:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> copied_dict = sample_dict.copy()
>>> copied_dict
{'email': 'jdoe@gmail.com', 'first_name': 'James', 'last_name': 'Doe'}

If your dictionary has objects or dictionaries inside of it, then you may end up running into logic errors due to this method as changing one dictionary can affect the copy. In those case, you should use Python’s copy module, which has a deepcopy function that will create a completely separate copy for you.

d.items()

The items() method will return a new view of the dictionary’s items:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict.items()
dict_items([('first_name', 'James'), ('last_name', 'Doe'), ('email', 'jdoe@gmail.com')])

This view object will change as the dictionary object itself changes.

d.keys()

If you need to get a view of the keys that are in a dictionary, then keys() is the method for you. As a view object, it will provide you with a dynamic view of the dictionary’s keys. You can iterate over a view and also check membership view the in keyword:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> keys = sample_dict.keys()
>>> keys
dict_keys(['first_name', 'last_name', 'email'])
>>> 'email' in keys
True
>>> len(keys)
3

d.values()

The values() method also returns a view object, but in this case it is a dynamic view of the dictionary’s values:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> values = sample_dict.values()
>>> values
dict_values(['James', 'Doe', 'jdoe@gmail.com'])
>>> 'Doe' in values
True
>>> len(values)
3

d.pop(key[, default])

Do you need to remove a key from a dictionary? Then pop() is the method for you. The pop() method takes a key and an option default string. If you don’t set the default and the key is not found, a KeyError will be raised.

Here are some examples:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict.pop('something')
Traceback (most recent call last):
   Python Shell, prompt 146, line 1
builtins.KeyError: 'something'
>>> sample_dict.pop('something', 'Not found!')
'Not found!'
>>> sample_dict.pop('first_name')
'James'
>>> sample_dict
{'email': 'jdoe@gmail.com', 'last_name': 'Doe'}

d.popitem()

The popitem() method is used to remove and return a (key, value) pair from the dictionary. The pairs are returned in last-in first-out (LIFO) order. If called on an empty dictionary, you will receive a KeyError

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict.popitem()
('email', 'jdoe@gmail.com')
>>> sample_dict
{'first_name': 'James', 'last_name': 'Doe'}

d.update([other])

Update a dictionary with the (key, value) pairs from other, overwriting existing keys. Returns None.

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict.update([('something', 'else')])
>>> sample_dict
{'email': 'jdoe@gmail.com',
'first_name': 'James',
'last_name': 'Doe',
'something': 'else'}

Modifying Your Dictionary

You will need to modify your dictionary from time to time. Let’s assume that you need to add a new key, value pair:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict['address'] = '123 Dunn St'
>>> sample_dict
{'address': '123 Dunn St',
'email': 'jdoe@gmail.com',
'first_name': 'James',
'last_name': 'Doe'}

To add a new item to a dictionary, you can use the square braces to enter a new key and set it to a value.

If you need to update a pre-existing key, you can do the following:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict['email'] = 'jame@doe.com'
>>> sample_dict
{'email': 'jame@doe.com', 'first_name': 'James', 'last_name': 'Doe'}

In this example, you set sample_dict['email'] to jame@doe.com. Whenever you set a pre-existing key to a new value, you will overwrite the previous value.

Deleting Items From Your Dictionary

Sometimes you will need to remove a key from a dictionary. You can use Python’s del keyword for that:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> del sample_dict['email']
>>> sample_dict
{'first_name': 'James', 'last_name': 'Doe'}

In this case, you tell Python to delete the key “email” from sample_dict.

The other method for removing a key is to use the dictionary’s pop() method, which was mentioned in the previous section:

>>> sample_dict = {'first_name': 'James', 'last_name': 'Doe', 'email': 'jdoe@gmail.com'}
>>> sample_dict.pop('email')
'jdoe@gmail.com'
>>> sample_dict
{'first_name': 'James', 'last_name': 'Doe'}

When you use pop(), it will return the value that is being removed.

Wrapping Up

The dictionary data type is extremely useful. You will find it handy to use for quick lookups of all kinds of data. You can set the value of the key: value pair to any object in Python. So you could store lists, tuples, or objects as values in a dictionary.

If you need a dictionary that can create a default when you go to get a key that does not exist, you should take a look at Python’s collections module. It has a defaultdict class that is made for exactly that use case.

Related Reading

 

The post Python 101 – Learning About Dictionaries appeared first on The Mouse Vs. The Python.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...