This article will introduce dictionaries in Python, which are Python’s only built-in mapping type


1. Create a dictionary

Dictionaries are made up of pairs of keys and values. Keys can be of any immutable type. Common ones are strings and tuples

Dictionaries can be created using the literal {}, which separates adjacent items with, and keys and values with:

>>> Create an empty dictionary
>>> person = {}
>>> Create a dictionary with elements
>>> person = {'name': 'Jessica'.'age': 20}
Copy the code

Dictionaries can also be created using the dict() built-in function, whose arguments can be keyword arguments or other mapping types

>>> Create a dictionary by passing in the keyword argument
>>> worker1 = dict(name = 'Nancy', workerID = 200189)
>>> worker1
# {'name': 'Nancy', 'workerID': 200189}
>>> Create dictionaries from other mapping types
>>> worker2 = dict([('name'.'Tommy'), ('workerID'.201901)])
>>> worker2
# {'name': 'Tommy', 'workerID': 201901}
Copy the code

2. Index elements

Dictionaries index values by keys, usually in the format dict[‘KEY’]

>>> dic = {'Apple': 15.'Banana': 24.'Carrot': 36}
>>> If the specified key exists in the dictionary, the corresponding value is returned
>>> dic['Apple']
# 15
>>> # If the specified key does not exist in the dictionary, an error is raised, causing the program to interrupt
>>> dic['Ant']
# KeyError
Copy the code

You can also index with the get() method, which returns the default value None or other specified value if the dictionary does not contain the specified key

>>> dic = {'Apple': 15.'Banana': 24.'Carrot': 36}
>>> If the dictionary does not contain the specified key, the default value of None is returned
>>> dic.get('Ant')
# None
>>> The # argument has the specified return value, which is returned when the dictionary does not contain the specified key
>>> dic.get('Ant'.0)
# 0
Copy the code

You can also index with the setDefault () method, which returns the specified value when the dictionary does not contain the specified key and adds the key-value pair to the dictionary

>>> dic = {'Apple': 15.'Banana': 24.'Carrot': 36}
>>> If the specified key exists in the dictionary, the corresponding value is returned
>>> dic.setdefault('Apple'.49)
# 15
>>> If the specified key does not exist in the dictionary, return the specified value and add the key-value pair to the dictionary
>>> dic.setdefault('Ant'.49)
# 49
>>> dic
# {'Apple': 15, 'Banana': 24, 'Carrot': 36, 'Ant': 49}
Copy the code

3. Delete elements

The pop(KEY) method can be used to delete the dictionary entry and return the value of the specified KEY

>>> dic = {'A': 1 , 'B': 2 , 'C': 3 , 'D': 4 , 'E': 5}
>>> dic.pop('C')
# 3
Copy the code

You can also delete the last dictionary item using the popitem() method, returning the deleted item

>>> dic = {'A': 1 , 'B': 2 , 'C': 3 , 'D': 4 , 'E': 5}
>>> dic.popitem()
# ('E', 5)
Copy the code

You can also use the method clear() to delete all dictionary entries, which is done in-place and does not return anything

>>> dic = {'A': 1 , 'B': 2 , 'C': 3 , 'D': 4 , 'E': 5}
>>> dic.clear()
Copy the code

4. Add elements

The way dictionaries add elements is a bit special, they can be added by direct assignment, and this is a big difference between dictionaries and sequences

>>> # list
>>> li = ['Apple'.'Banana'.'Carrot']
>>> li[0] = 'Ant'      # (modify element) ok, the first item in the list becomes 'Ant'
>>> li[3] = 'Dog'      IndexError: List Assignment index out of range
>>> # dictionary
>>> dic = {'Apple': 15.'Banana': 24.'Carrot': 36}
>>> dic['Apple'] = 30  # (modify element) yes, the dictionary key 'Apple' becomes 30
>>> dic['Dog'] = 40    # (add element) works, add a new entry in the dictionary with the key 'Dog' and the value 40
Copy the code

In addition, the update() method allows you to update one dictionary with another

If the current dictionary does not have a corresponding key value, add it; If the current dictionary contains an item with the same key, replace it

>>> dic1 = {'A': 1 , 'B': 2}
>>> dic2 = {'B': 3 , 'D': 4}
>>> dic1.update(dic2)
>>> dic1
# {'A': 1, 'B': 3, 'D': 4}
Copy the code

5. Dictionary iteration

There are three methods: keys() returns all the keys in the dictionary, values() returns all the values in the dictionary, and items() returns all the items in the dictionary

>>> dic = {'A': 1.'B': 2.'C': 3}

>>> # Iterate over the keys in the dictionary
>>> for key in dic.keys(): print(key)
# A
# B
# C

>>> # Iterate over the values in the dictionary
>>> for value in dic.values(): print(value)
# 1
# 2
# 3

>>> # Iterate over the entries in the dictionary
>>> for item in dic.items(): print(item)
# ('A', 1)
# ('B', 2)
# ('C', 3)
Copy the code

All three methods return a type called a dictionary view, which is always a reflection of the underlying dictionary

>>> dic = {'A': 1.'B': 2.'C': 3}
>>> items = dic.items()
>>> items
# dict_items([('A', 1), ('B', 2), ('C', 3)])
>>> dic['A'] = 3
>>> items
# dict_items([('A', 3), ('B', 2), ('C', 3)])
Copy the code

6. Dictionary derivation

Dictionary derivations are similar to list derivations and can be used to quickly create dictionaries. The basic format is as follows:

dic = {key_expression(i):value_expression(i) for i in可迭代if condition(i)}
Copy the code

Translate into general statement:

dic = {}
for i in iterable:
    if condition(i):
        dic[key_expression(i)] = value_expression(i)
Copy the code
  • Example 1: Give a list of strings, build a dictionary with strings as keys and string lengths as values
>>> li = ['I'.'Love'.'Python']
>>> dic = {i:len(i) for i in li}
>>> dic
# {'I': 1, 'Love': 4, 'Python': 6}
Copy the code
  • Example 2: Give the original dictionary, swap keys and values, and create a new dictionary
>>> old_dict = {'A': 1.'B': 2.'C': 3}
>>> new_dict = {v:k for k,v in old_dict.items()}
>>> new_dict
{1: 'A'.2: 'B'.3: 'C'}
Copy the code

7. Dictionary sort

Sorted dictionaries can be sorted using the sorted() function, which always returns a sequence

  • Example 1: Key sorting
>>> old = {1: 'E'.5: 'A'.2: 'D'.4: 'B'.3: 'C'}
>>> new = sorted(old.items(), key = lambda x: x[0])
>>> new
# [(1, 'E'), (2, 'D'), (3, 'C'), (4, 'B'), (5, 'A')]
Copy the code
  • Example 2: Sort by value
>>> old = {1: 'E'.5: 'A'.2: 'D'.4: 'B'.3: 'C'}
>>> new = sorted(old.items(), key = lambda x: x[1])
>>> new
# [(5, 'A'), (4, 'B'), (3, 'C'), (2, 'D'), (1, 'E')]
Copy the code