mapping The object will hashable Value maps to any object . The mapping belongs to a mutable object . Currently, there is only one standard mapping type Dictionaries . ( For other container objects, see list
, set
And tuple
And other built-in classes , as well as collections
modular .)
Key to dictionary almost It can be anything . Not hashable Value , Include list 、 Dictionary or other variable type value ( Such objects are compared based on values rather than object identifiers ) Cannot be used as a key . When a number type is used as a key, it follows the general rule of number comparison : If the two values are equal ( for example 1
and 1.0
) Then both can be used to index the same dictionary entry . ( But notice , Because the computer stores only approximate values for floating-point numbers , Therefore, it is unwise to use it as a dictionary key .) Dictionaries can be separated by commas key : value
The list of pairs is enclosed in curly braces to create , for example : {'jack': 4098, 'sjoerd': 4127}
or {4098: 'jack', 4127: 'sjoerd'}
, It can also be done through dict
Constructor to create .class dict
(**kwargs)class dict
(mapping, **kwargs)class dict
(iterable, **kwargs)
Return to a new dictionary , Initialize based on optional positional parameters and possibly empty keyword parameter sets .
Dictionaries can be created in many ways :
key : value
Right way : {'jack': 4098, 'sjoerd': 4127}
or {4098: 'jack', 4127: 'sjoerd'}
{}
, {x: x ** 2 for x in range(10)}
dict()
, dict([('foo', 100), ('bar', 200)])
, dict(foo=100, bar=200)
If the position parameter is not given , An empty dictionary will be created . If a position parameter is given and it belongs to the mapping object , A dictionary with the same key value pairs as the mapping object will be created . Otherwise , The position parameter must be a iterable object . Each item in the iteratable object itself must be an iteratable object that contains exactly two elements . The first object in each item will become a key in the new dictionary , The second object will become its corresponding value . If a key appears more than once , The last value of the key will become its corresponding value in the new dictionary .
If a keyword parameter is given , Then the keyword parameter and its value will be added to the dictionary created based on the location parameter . If the key to be added already exists , The value from the keyword parameter replaces the value from the location parameter .
As a demonstration , The dictionaries returned by the following examples are all equal to {"one": 1, "two": 2, "three": 3}
:
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> f = dict({'one': 1, 'three': 3}, two=2)
>>> a == b == c == d == e == f
True
As in the first example, the way to provide keyword parameters can only use valid Python Identifier as key . Other methods can use any valid key .
These are the operations supported by the dictionary ( Therefore, custom mapping types should also support ):
list(d)
Return dictionary d A list of all the keys used in .
len(d)
Return dictionary d Number of items in .
d[key]
return d China and Israel key Is the key's item . If the mapping does not exist key Will trigger KeyError
. If a subclass of the dictionary defines a method __missing__()
also key non-existent , be d[key]
The operation will call the method with the key key As a parameter . d[key]
Will then return or raise __missing__(key)
Any object or exception returned or thrown by the call . No other operation or method will initiate the call __missing__()
. If not defined __missing__()
, Will trigger KeyError
. __missing__()
It has to be a way ;
>>> class Counter(dict):
... def __missing__(self, key):
... return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1
>>> d = {'a': 1}
>>> d.values() == d.values()
False
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(reversed(d))
['four', 'three', 'two', 'one']
>>> list(reversed(d.values()))
[4, 3, 2, 1]
>>> list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]