web123456

Use of Python dictionary dict

This article covers almost all the methods of using dictionary dict, which is easy to learn quickly and is easy to read during use.
Other types of operations:StringListgather

Table of contents

  • dictionary
  • Get the value (get(), setdefault())
  • Modify and add values ​​(update())
  • Delete (del, pop(), popitem() clear())
  • Length (len())
  • Keys, values, pairs (keys(), values(), items(), list(), reversed())
  • in and not in
  • Iterate (iter())
  • Copy (copy())

dictionary

A dictionary is mapped from one object to another. The index of the dictionary is called a key, and it is best not to be a floating point number. The value of the dictionary can be a dictionary, a list, or other variable sequence. The key and its associated values ​​are called key-value pairs.

cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
  • 1

Dictionary by braces{and}Beginning and ending, colon:The front represents the key, the colon represents the value, and multiple key-value pairs are separated by commas. Keys are referenced as value indexes, such as

cat['size']   # 'fat'
  • 1

dictThe constructor can accept various forms of parameters, creating an empty dictionary without any parameters. The parameter must have two parts, and both are required to be an iterable object, the first part as the key and the second part as the value.

dict([(a, 100), (b, 200)])   # {'a': 100, 'b': 200}
dict(one=1, two=2, three=3)  # {'one': 1, 'two': 2, 'three': 3}
  • 1
  • 2

You can also use list comprehension to generate dictionaries

{x: x**2 for x in range(3)}  # {0: 0, 1: 1, 2: 4}
  • 1

Get the value (get(), setdefault())

If you need to get the value of a certain key, you only need to enter the key in a similar way to the subscript.

cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
cat['size']  # 'fat'
  • 1
  • 2

If the entered key does not exist, aKeyErrorofabnormal

If you do not want to throw an exception, you can useget()method.get()The method has 2 parameters, the first parameter is the key, and the second parameter indicates the backup value returned if the key does not exist, and the default isNone. like

cat.get('name', 0)   # 0
  • 1

setdefault()The method is used to return a value. If the key does not exist, add a key-value pair to the dictionary and return the value. This value is defaulted toNone

cat.setdefault('name', 'Kitty')
  • 1

Modify and add values ​​(update())

The value can be directly modified by subscript.

cat['color'] = 'black'   # {'size': 'fat', 'color': 'black', 'disposition': 'loud'}
  • 1

If the key does not exist, add a key-value pair.

cat['name'] = 'Kitty'  
# {'size': 'fat', 'color': 'black', 'disposition': 'loud', 'name': 'Kitty'}
  • 1
  • 2

update()Methods can add values ​​to the dictionary, parameters can be dictionary, or other iterable key-value pairs.

cat.update({'name': 'Kitty'})  
# {'size': 'fat', 'color': 'gray', 'disposition': 'loud', 'name': 'Kitty'}
  • 1
  • 2

|It can also be usedupdate()The function of , it must act on the dictionary.

cat |= {'name': 'Kitty'}
  • 1

|forpython3.8 New content.

Delete (del, pop(), popitem() clear())

delYou can delete a key-value pair. If the key does not exist, an exception is thrown.

del cat['name']
  • 1

popanddelThe difference between deletion ispopwill return the value, anddelWon't.

cat.pop('size')    # Return 'gray', cat = {'color': 'gray', 'disposition': 'loud'}
  • 1

If the key does not exist, the default return value can be set, otherwise an exception will be thrown.

cat.pop('name', 'No name')   # 'No name'
  • 1

pop()Only the value returned, if you need to return a key-value pair, usepopitem()method.

cat.popitem()
  • 1

This method deletes values ​​arbitrarily from the dictionary, suitable for iteration.

clear()Method clear the dictionary.

cat.clear()   # {}
  • 1

Length (len())

len()Returns how many key-value pairs are in the dictionary.

len(cat)
  • 1

Keys, values, pairs (keys(), values(), items(), list(), reversed())

keys()values()anditems()The key, value and key-value pairs corresponding to the dictionary are respectivelydict_keysdict_valuesanddict_items, their values ​​cannot be modified. Available forforcycle.

cat.keys()    # dict_keys(['size', 'color', 'disposition'])
cat.values()  # dict_values(['fat', 'gray', 'loud'])
cat.items()   # dict_items([('size', 'fat'), ('color', 'gray'), ('disposition', 'loud')])
  • 1
  • 2
  • 3

list()Methods can obtain a list of keys for the dictionary.

list(cat)         # ['size', 'color', 'disposition']
list(cat.keys())  # Equivalent
  • 1
  • 2

reversed()Returns a reverse order keyIterator. You can also directly reverse key-value pairs.

reversed(cat)
reversed(cat.keys()) # Equivalent
reversed(cat.items())
  • 1
  • 2
  • 3

reversed()Added new content for python 3.8.

in and not in

Check whether a key or value exists in the dictionary, returnTrueorFalse. like

cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
'name' in cat.keys()    # False
'size' in cat.keys()    # True
'name' not in cat.keys()  # True
'size' not in cat.keys()  # False
'fat' in cat.values()  # True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

In the above codekeys()Can be omitted. like

'name' in cat   # equivalent to 'name' in ()
  • 1

Iterate (iter())

iter()Returns the iterator for the dictionary key.

iter(cat)
iter(cat.keys()) # Equivalent
  • 1
  • 2

Copy (copy())

copy()Returns a shallow copy of the dictionary. Can also be usedcopy module