官术网_书友最值得收藏!

Dictionaries in Python

Dictionaries are very powerful structures and are widely used in Python. A dictionary is a key-value pair structure. A dictionary key can be a unique number or string, and the value can be any Python object. Dictionaries are mutable and can be changed in place. The following example demonstrates the basics of dictionaries in Python:

A Python dictionary can be declared within curly braces. Each key value pair is separated by a comma. It should be noted that the keys have to be unique; if we try to repeat the keys, the old key value pair is overwritten by the new one. From the preceding example, we can establish that the dictionary keys can be either string or numeric types. Let's try to perform various operations on dictionaries in Python:

  • Retrieving the dictionary values with the keys: Dictionary values can be accessed through the name of the dictionary key. If the name of the key is not known, we can use loops to iterate through the whole dictionary structure. We will cover this in the next chapter of this book:

This is one of the many ways to print dictionary values. However, if the key for which the value we wish to print does not exist in the dictionary, we will get a key not found exception, as shown in the following screenshot:

There is a better way to handle this and avoid these kinds of exceptions. We can use the get() method provided by the dictionary class. The get() method takes the key name as the first argument and the default value if the key is not present as the second argument. Then, instead of throwing an exception, the default value will be returned if the key is not found. This is shown in the following screenshot:

In the preceding example, when the k1 key is present in the actual dictionary, dict1, the value for the k1 key is returned, which is v1. Then, the k0 key was searched, which was not present originally. In that case, no exception was raised, but instead the False value was returned, suggesting that no such key, K0, was actually present. Remember that we can specify any placeholder as the second argument to the get() method to indicate the absence of the key we are searching for.

  • Adding keys and values to the dictionary: Once a dictionary has been declared, over the course of the code, there could be many occasions in which we want to modify a dictionary key or add a new dictionary key and value. This can be achieved as follows. As mentioned earlier, a dictionary value can be any Python object, so we can have tuples, lists, and dictionary types as values inside a dictionary:

Now, let's add more complex types as values:

These values can be retrieved as normal values by their keys as follows:

  • Expanding a dictionary with the contents of another dictionary: In the preceding example,we added a dictionary as a value to an existing dictionary. We will now see how can we merge two dictionaries into one common or new dictionary. The update() method can be used to do this:
  • Keys(): To get all the dictionary keys, we can use the keys() method. This returns the class instances of the dictionary keys:

We can see that the keys method returns an instance of the dict_keys class, which holds the list of dictionary keys. We can type cast this as a list type as follows:

  • values(): The values() method returns all the values that are present in the dictionary:
  • Items(): This method is actually used to iterate over the dictionary key value pairs, as it returns a list class instance that contains a list of tuples. Each tuple has two entries, the first one being the key and the second one being the value:

We can convert the returned class instance into a tuple, list tuple, or list type as well. The ideal way to do this is to iterate over the items, which we will see later when we look at loops:

  • in and not in: The in and not in methods are used to see whether a key is present in the dictionary or not. By default, the in and not in clauses will search the dictionary keys, not the values. Take a look at the following example:
  • Order of storing: By default, Python dictionaries are unordered, which means they are not stored internally in the same order as we define them. The reason for this is that the dictionaries are stored in dynamic tables called hash tables. As these tables are dynamic, they can increase and shrink in size. What happens internally is that a hash value of the key is computed and stored in the table. The key goes in the first column, while the second column holds the actual value. Let's take a look at the following example to explain this better:

In the preceding case, we declare a dictionary, a, with the first key as abc and the second key as abcd. When we print the values, however, we can see that abcd is stored internally before abc. To explain this, let's assume that the dynamic table or hash table in which the dictionary is internally stored is of size 8.

As we mentioned earlier, the keys will be stored as hash values. When we compute the hash of the abc string and and divide it in a modular fashion by 8, which is the table size, we get the result of 7. If we do the same for abcd, we get a result of 4. This means that the hash abcd will be stored at index 4, while the hash abc will be stored at index 7. For this reason, in the listing, we get abcd listed before abc:

There may be occasions in which two keys arrive at a common value after the hash(key)%table_size operation, which is called a collision. In this case, the key to be slotted first is the one that is stored first.

  • sorted(): If we want our dictionary to be sorted according to the keys, we can use the built-in sorted method. This can be tweaked to return a list of tuples, with each tuple having a key at the 0th index and its value at the 1st index:

  • Removing elements: We can use the conventional del statement to delete any dictionary item. When we say delete, we mean delete both the key and the value. Dictionary items work in pairs, so deleting the key would remove the value as well. Another way to delete an entry is to use the pop() method and pass the key as an argument. This is shown in the following code snippet:
主站蜘蛛池模板: 砀山县| 蓝田县| 清涧县| 潞城市| 荔浦县| 如皋市| 偃师市| 阜平县| 河南省| 太康县| 油尖旺区| 长沙县| 金昌市| 阳泉市| 上蔡县| 苗栗县| 蓝田县| 永城市| 三亚市| 个旧市| 达日县| 卢氏县| 张家界市| 维西| 金昌市| 略阳县| 宁武县| 深州市| 昔阳县| 渝中区| 富裕县| 河北区| 奎屯市| 遂宁市| 平塘县| 商河县| 泗水县| 娄烦县| 安岳县| 克山县| 武强县|