Dictionaries in python are described in detail

  • 2020-04-02 14:09:42
  • OfStack

What is a dictionary?

Dictionaries are the only mapping type in the Python language.

The hash value (key, key) and the pointing object (value, value) in the mapping type object are one-to-many relationships, which are often considered as mutable hash tables.

The dictionary object is mutable; it is a container type that can store any number of Python objects, including other container types.

The difference between dictionary type and sequence type:

1. Different ways of accessing and accessing data.
2. Only numeric keys are used for sequence types (indexed numerically from the beginning of the sequence);
Map types can use other object types as keys (such as Numbers, strings, primitives, and generally strings as keys). Unlike sequence types, map types have keys directly associated with stored data values.
5. The data in the map type is unordered. This is different from sequence types, which are arranged in numerical order.
6. Map types "map" directly to values with keys.

Dictionaries are one of the most powerful data types in Python.

How to create and assign a value to a dictionary

A dictionary is simply a collection of key-value pairs wrapped in braces. (key-value pairs are also called items.)
General form:


adict = {}
adict = {key1 : value2 . key2 : value2 . ... }

Or the dict() function, such as adict = dict() or adict = dict((['x',1],['y',2])). Adict = dict (['x',1],['y',2]). Create a dictionary with keyword parameters such as: adict= dict(name=' Allen ',age='40 ')
Or use the fromkeys() method, such as adict = {}. Fromkeys ((' x','y'), -1).

Features:
1. The key and value are separated by the colon ":";
2. Separate items with comma ", ";
3. Keys in dictionaries must be unique, and values may not be unique.


adict = { ' name':'allen', ' name':'lucy', ' age':'40 ' } with bdict = { ' name':'allen', ' name2 ' :'allen', ' age':'40 ' }

Note: if the dictionary value is a number, it is better to use the string numeric form, such as 'age':'040 'instead of 'age': 040

Three, the basic operation of the dictionary

1. How do I access the values in the dictionary?
The adict[key] form returns the value corresponding to the key, and raises a KeyError if the key is not in the dictionary.

2. How to check whether the key is in the dictionary?

A, has_key() method, such as: adict.haskey(' name') has a copy > True, no � > False
B, in, not in     'name' in adict           A � > True, no � > False

3. How to update the dictionary?

A. Add a data item (new element) or key-value pair
Adict [new_key] = add an item in the form of value
B. Update a data item (element) or key-value pair
Adict [old_key] = new_value
C. Delete a data item (element) or key-value pair
Del adict[key] deletes the key entry/del adict deletes the entire dictionary
Adict.pop (key) deletes the item of the key and returns the value corresponding to the key

Mapping type operators

Standard type operator (+, -, *, < . > . < =, > = = =,! =, and, or, not)

A. dictionaries do not support splicing and repetition operators (+, *)
B. dictionary comparison operations
Let's compare the length of the dictionary which is the number of elements in the dictionary
The key is
Value comparison
Example:


adict = {}
bdict = { ' name':'allen', ' age':'40 ' }
cmp(adict, bdict)  < � >-1 or > � >1 or ==  � >0

Mapping related functions

Len () returns the length of the dictionary
Hash () returns the hash value of an object to determine whether an object can be used as a key for a dictionary
Dict () factory function, used to create a dictionary

Six, the dictionary method

1. Adict. keys() returns a list of all the keys in the dictionary;
Adict.values () returns a list of all dictionary values;
Adict. items() returns a list of all (key, value) primitives.
4. Adict. clear() delete all items or elements in the dictionary;
5. Adict.copy () returns a copy of a shallow copy of the dictionary;
6. Adict. fromkeys(seq, val=None) creates and returns a new dictionary, with the element in seq as the key of the dictionary, and val as the initial value corresponding to all keys in the dictionary (default is None);
7. Adict. get(key, default = None) returns the value corresponding to the key in the dictionary.
If the key is in the dictionary, return True; otherwise, False. Now use in, not in;
9. Adict. iteritems(), adict.iterkeys(), and adict.itervalues() are the same as their noniterative counterparts, except that they return an iteron instead of a list.
10. Adict. pop(key[,default]) is similar to the get method. If there is a key in the dictionary, delete and return the corresponding vuale; If the key does not exist and the value of default is not given, a keyerror exception is thrown.
11. Adict. setdefault(key, default=None) is similar to set(), but if there is no key in the dictionary, the adict[key] = default will assign a value to it;
12. Adict. update(bdict) adds the key value pair of dictionary bdict to the dictionary adict.

Dictionary traversal

1. The key of traversing the dictionary


for key in adict.keys():print key

2. Traversing the value of the dictionary

for value in adict.values(): print value

3. Traversing the entries (elements) of the dictionary

for item in adict.items():print item

4. Traverse the key-value of the dictionary

for item . value in adict.items(): print ' key=%s, value=%s' %(item, value)  or    for item . value in adict.iteritems(): print ' key=%s, value=%s' %(item, value)

Note: for item,value in adict.items(): print 'key=%s',' value=%s', %(item, value) is wrong

Notes on using a dictionary

1. One key cannot correspond to multiple values;
2. Keys must be hashed.


Related articles: