Chapter 4 when indexing doesn't work

This chapter introduces a data structure whose values can be accessed by name. This is called mapping. Dictionary is the only built-in mapping type in Python, in which the values are not arranged in order, but stored under the key. Keys can be numbers, strings, or tuples.

4.1 purpose of dictionary

4.2 creating and using dictionaries

phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

The dictionary consists of keys and their corresponding values, which are symmetrical as item s.
An empty dictionary (without any entries) is represented by two curly braces, similar to the following: {}.

4.2.1 function dict

You can use the function dict1 to create dictionaries from other mappings (such as other dictionaries) or sequences of key value pairs.

>>> items = [('name', 'Gumby'), ('age', 42)] 
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name'] 

You can also call this function with keyword arguments.

>>> d = dict(name='Gumby', age=42) 
>>> d
{'age': 42, 'name': 'Gumby'}

If this function is called without any arguments, an empty dictionary is returned.
When creating a dictionary from a map, if the map is also a dictionary, you can use the dictionary method copy instead of the function dict.

4.2.2 basic dictionary operation

The basic behavior of a dictionary is similar to a sequence in many ways.

  • len(d) returns the number of items (key value pairs) contained in dictionary D.
  • d[k] returns the value associated with key K.
  • d[k] = v associates the value v to the key K.
  • del d[k] delete the item with key K.
  • k in d checks whether dictionary d contains items with key k.

Although dictionaries and lists have many similarities, they also have some important differences.

  • Key type: the key in the dictionary can be any immutable type, such as floating point number (real number), string or tuple.
  • Auto add: even a key not originally in the dictionary can be assigned a value, which will create a new item in the dictionary. If you do not use append or other similar methods, you cannot assign values to elements that are not in the list.
>>> x = []
>>> x[42] = 'Foobar'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list assignment index out of range >>> x = {}
>>> x[42] = 'Foobar'
>>> x
{42: 'Foobar'}
  • Membership: the expression K in d (where d is a dictionary) looks for keys rather than values, while the expression V in L (where l is a list) looks for values rather than indexes.

It is more efficient to check whether the dictionary contains the specified key than to check whether the list contains the specified value. The larger the data structure, the greater the efficiency gap.

4.2.3 use string format setting function for dictionary


4.2.4 dictionary method

The dictionary method is useful, but it may not be used as frequently as the list and string methods.

  1. clear
    Delete all dictionary items and execute them locally (like list.sort), so nothing is returned (return None).
>>> d
{'age': 42, 'name': 'Gumby'} 
>>> returned_value = d.clear() 
>>> d
>>> print(returned_value)

# Why is this useful? Look at two scenarios.
# First scenario:
>>> x = {}
>>> y = x
>>> x['key'] = 'value' >>> y
{'key': 'value'}
>>> x = {}
>>> x = {}
{'key': 'value'}
# Second scenario:
>>> x = {}
>>> y = x
>>> x['key'] = 'value' >>> y
{'key': 'value'}
>>> x.clear()
>>> y
# In both scenarios, x and y initially point to the same dictionary.
# In the first scenario, an empty dictionary is assigned to x to "empty" it. This has no effect on y, it still points to the original dictionary. This behavior may be exactly what you want.
# However, to delete all elements of the original dictionary, you must use clear. If you do, y will also be empty.
  1. copy
    Returns a new dictionary containing the same key value pairs as the original dictionary (this method performs a shallow copy because the value itself is an original, not a copy).
>>> x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']} 
>>> y = x.copy()
>>> y['username'] = 'mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo', 'baz']}
>>> x
{'username': 'admin', 'machines': ['foo', 'baz']}
# When the value in the copy is replaced, the original is not affected. However, if the value in the copy is modified (modified in place rather than replaced), the original will also change because the original also points to the modified value (as shown in the 'machines' list in this example).

# One way to avoid this problem is to perform a deep copy, that is, copy values and all their contained values at the same time, and so on. To do this, use the function deepcopy in the module copy.
>>> from copy import deepcopy
>>> d = {}
>>> d['names'] = ['Alfred', 'Bertrand'] 
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d['names'].append('Clive')
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']} 
>>> dc
{'names': ['Alfred', 'Bertrand']}
  1. fromkeys
    Create a new dictionary containing the specified keys, and the corresponding value of each key is None.
>>> {}.fromkeys(['name', 'age']) 
{'age': None, 'name': None}
# First, an empty dictionary is created, and then the method fromkeys is called to create another dictionary.
# Instead of doing this, you can directly call the method fromkeys on dict (as mentioned earlier, dict is the type of all dictionaries. Classes and types will be discussed in detail in Chapter 7).
>>> dict.fromkeys(['name', 'age']) 
{'age': None, 'name': None}
# If you do not want to use the default value None, you can provide a specific value.
>>> dict.fromkeys(['name', 'age'],'(unknown)') 
{'age': '(unknown)', 'name': '(unknown)'}
  1. get
    Provides a relaxed environment for accessing dictionary items. Typically, an attempt to access an item that is not in the dictionary will cause an error.
>>> d = {}
>>> print(d['name'])
Traceback (most recent call last):
File "<stdin>", line 1, in ? KeyError: 'name'
# When using get to access a nonexistent key, no exception is thrown, but None is returned
>>> print(d.get('name'))
# You can specify a default value, which returns the specified value instead of None
>>> d.get('name', 'N/A') 
# If the dictionary contains the specified key, the function of get will be the same as that of ordinary dictionary lookup.
>>> d['name'] = 'Eric' 
>>> d.get('name') 
  1. items
    Returns a list of all dictionary items, where each element is in the form of (key, value). The order of dictionary items in the list is uncertain.
>>> d = {'title': 'Python Web Site', 'url': '', 'spam': 0} 
>>> d.items()
dict_items([('url', ''), ('spam', 0), ('title', 'Python Web Site')])
# The return value belongs to a special type called dictionary view. The dictionary view can be used for iterations. In addition, you can determine its length and perform membership checks on it
>>> it = d.items() 
>>> len(it)
>>> ('spam', 0) in it 

# One advantage of views is that they are not copied. They are always a reflection of the underlying dictionary, even if the underlying dictionary is modified:
>>> d['spam'] = 1
>>> ('spam', 0) in it 
>>> d['spam'] = 0
>>> ('spam', 0) in it 
# To copy dictionary items to the list (as the method items did in older Python versions), do it yourself.
>>> list(d.items())
[('spam', 0), ('title', 'Python Web Site'), ('url', '')]
  1. keys
    Returns a dictionary view containing the keys in the specified dictionary.
  2. pop
    Can be used to get the value associated with the specified key and remove the key value pair from the dictionary.
>>> d = {'x': 1, 'y': 2} 
>>> d.pop('x')
>>> d
{'y': 2}
  1. popitem
    It is similar to list.pop, but list.pop pops up the last element in the list, while popitem randomly pops up a dictionary item, because the order of dictionary items is uncertain and there is no concept of "last element". This can be useful if you want to efficiently delete and process all dictionary items one by one, because you don't need to get the key list first.
>>> d = {'url': '', 'spam': 0, 'title': 'Python Web Site'} 
>>> d.popitem()
('url', '')
>>> d
{'spam': 0, 'title': 'Python Web Site'}
# If you want the method popitem to pop up dictionary entries in a predictable order, see the OrderedDict class in module collections.
  1. setdefault
    It is a bit like get because it also gets the value associated with the specified key, but in addition, setdefault adds the specified key value pair to the dictionary when the dictionary does not contain the specified key.
>>> d = {}
>>> d.setdefault('name', 'N/A') 
>>> d
{'name': 'N/A'}
>>> d['name'] = 'Gumby'
>>> d.setdefault('name', 'N/A') 
>>> d
{'name': 'Gumby'}
# When the specified key does not exist, setdefault returns the specified value and updates the dictionary accordingly.
# If the specified key exists, its value is returned and the dictionary remains unchanged.
# Like get, the value is optional; If not specified, it defaults to None.
>>> d = {}
>>> print(d.setdefault('name')) None
>>> d
{'name': None}
  1. update
    Use items from one dictionary to update another dictionary.
>>> d = {
'title': 'Python Web Site',
'url': '',
'changed': 'Mar 14 22:09:15 MET 2016'
>>> x = {'title': 'Python Language Website'}
>>> d.update(x)
>>> d
{'url': '', 
'changed':'Mar 14 22:09:15 MET 2016', 
'title': 'Python Language Website'}
# For dictionaries provided through parameters, add their entries to the current dictionary.
# If the current dictionary contains an item with the same key, replace it.

# The method update can be called like the function dict (type constructor) discussed earlier in this chapter. This means that when you call update, you can provide it with a map, a sequence of key value pairs (or other iteratable objects), or keyword parameters.
  1. values
    Returns a dictionary view consisting of values from a dictionary. Unlike method keys, the view returned by method values may contain duplicate values.
>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d[3] = 3
>>> d[4] = 1
>>> d.values() 
dict_values([1, 2, 3, 1])

Tags: Python Back-end

Posted on Wed, 10 Nov 2021 19:47:11 -0500 by ratass2002