A detailed introduction to the dictionary in python and a detailed introduction to the python dictionary

Source: Internet
Author: User

A detailed introduction to the dictionary in python and a detailed introduction to the python dictionary

1. What is a dictionary?

A dictionary is the only ing type in Python.

In a ing object, the hash value (key, key) has a one-to-many relationship with the object (value, value), which is generally considered a variable hash table.

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

Differences between the dictionary type and the sequence type:

1. The methods for accessing and accessing data are different.
2. sequence types only use numeric keys (index from the beginning of the sequence in numerical order );
3. the ing type can use other object types as keys (such as numbers, strings, and ancestor, usually strings as keys). Different from the sequence type keys, the ing type keys are straight 4. connect or indirectly associate with stored data values.
5. Data in the ing type is unordered. This is different from the sequence type. The sequence type is arranged in numerical order.
6. The ing type is directly "mapped" to the value with the key.

A dictionary is one of the most powerful data types in Python.

Ii. How to Create a dictionary and assign values to the dictionary

In short, the dictionary is a set of key-value pairs enclosed in braces. (Key-value pairs are also called items)
General format:
Copy codeThe Code is as follows:
Adict = {}
Adict = {key1: value2, key2: value2 ,...}

Or use the dict () function, for example, adict = dict () or adict = dict (['x', 1], ['y', 2]). is this correct? Adict = dict (['x', 1], ['y', 2]). Keyword parameter creation dictionary, such as: adict = dict (name = 'allen', age = '40 ′)
Or use the fromkeys () method, for example, adict = {}. fromkeys ('x', 'y'),-1) creates the same dictionary value. If no value is given, the default value is None.

Features:
1. separate keys and values with the colon;
2. Separate items with commas;
3. the keys in the dictionary must be unique, but the values may not be unique.
Copy codeThe Code is as follows:
Adict = {'name': 'allen ', 'name': 'Lucy', 'age': '40'} And bdict = {'name': 'allen ', 'name2': 'allen ', 'age': '40 ′}

Note: If the value in the dictionary is a number, it is best to use a string number, for example, 'age': '040' instead of 'age': 040

3. Basic dictionary operations

1. How to access the value in the dictionary?
Return the value corresponding to the key in the form of adict [key]. If the key is not in the dictionary, a KeyError is thrown.

2. How do I check whether the key is in the dictionary?

A. The has_key () method is like: adict. haskey ('name') has-> True, none-> False
B. in and not in shapes such as: 'name' in adict has-> True, no-> False

3. How to update the dictionary?

A. Add a data item (new element) or key-Value Pair
Add an item in the form of adict [new_key] = 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] Delete the key item/del adict Delete the entire dictionary
Adict. pop (key) deletes the key and returns the value corresponding to the key.

Iv. ing type operators

Standard Type Operators (+,-, *, <,>, <=, >=, = ,! =, And, or, not)

A. the dictionary does not support concatenation and repetition operators (+ ,*)
B. Comparison of dictionaries
First, compare the length of the dictionary, that is, the number of dictionary elements.
Key comparison
Value Comparison
Example:
Copy codeThe Code is as follows:
Adict = {}
Bdict = {'name': 'allen ', 'age': '40 ′}
Cmp (adict, bdict) <->-1 or>-> 1 or =-> 0

V. ing Functions

1. len () returns the length of the dictionary.
2. hash () returns the hash value of an object, which can be used to determine whether an object can be used as a dictionary key.
3. dict () Factory functions used to create dictionaries

6. dictionary Methods

1. adict. keys () returns a list Of all keys in the dictionary;
2. adict. values () returns a list containing all values in the dictionary;
3. adict. items () returns a list containing all (Key, value) ancestor;
4. adict. clear () deletes all items or elements in the dictionary;
5. adict. copy () returns a copy of the dictionary;
6. adict. fromkeys (seq, val = None) is created and a new dictionary is returned. The dictionary key is used as an element in seq, val is the initial value corresponding to all keys in the dictionary (the default value is None );
7. adict. get (key, default = None) returns the value corresponding to the key in the dictionary. If the key does not exist in the dictionary, the default value is returned (default is None );
8. adict. has_key (key) returns True if the key is in the dictionary; otherwise, False is returned. Use in, not in;
9. adict. iteritems (), adict. iterkeys (), adict. itervalues () is the same as their non-iterative methods. The difference is that they return an iterator instead of a list;
10. The adict. pop (key [, default]) and get methods are similar. If the dictionary contains a key, the corresponding vuale of the key is deleted and returned. If the key does not exist and the default value is not given, a keyerror exception is thrown;
11. The adict. setdefault (key, default = None) method is similar to the set () method, but if the Key does not exist in the dictionary, adict [key] = default assigns a value to it;
12. adict. update (bdict) adds the key-value pairs of the dictionary bdict to the dictionary adict.

VII. dictionary Traversal

1. traverse the dictionary key (key)
Copy codeThe Code is as follows:
For key in adict. keys (): print key

2. traverse the dictionary value (value)
Copy codeThe Code is as follows:
For value in adict. values (): print value

3. Traverse dictionary items (elements)
Copy codeThe Code is as follows:
For item in adict. items (): print item

4. traverse the dictionary's key-value
Copy codeThe Code is as follows:
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 incorrect.

8. Precautions for using dictionaries

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


Python dictionary list and list dictionary

The most essential difference: the first method produces a list, and the second method is a dictionary.
The python statement is as follows:
1. type (a) = list
2. type (a) = dict
In the interactive interface, display:
First:
>>>
[{'Name': 'fokil '}]
At this time, a is a list. It has all the methods and attributes of the list, but does not have any dictionary methods and attributes. The list can have N elements. The element type is arbitrary and has nothing to do with the List itself. At this time, a has an element, which is a dictionary -- but this does not mean that the entire list a has any dictionary. Understand?
Second:
>>>
{'Name': ['fokil ']}
Same as above. At this time, a is a dictionary that has all the methods and attributes of the dictionary, but does not have any list of methods and attributes. A dictionary can contain N elements. Each element is composed of a combination of keys and content. A key can be of any single object type (not a list or dictionary-but a tuples. Of course, it can also be numbers, characters/strings, or even file objects), and the content corresponding to the key can be of any type. At this time, a has only one element, the key is a string, and the content is a list containing a string element-Similarly, this does not mean that a has any list nature.
Strictly speaking, there is no dictionary list or list dictionary concept.
There is only one list, and its element type is dictionary-of course, the elements in the list can be of different types, such:
A = [1, 'test', [2, 3, 4], {'name': 'fokil '}]
Similarly, there is only one dictionary, and part of its elements is a list (of course, the key part cannot be a list ). Of course, it may also be different types of elements:
A = {1: 'B', (, 3): [, 6], 'test': {'test2': ['test3']}

Sort dictionaries in python

>>> D
{'A': 1, 'World': 11, 'z': 9, 'Hello': 10}
>>> K = d. keys ()
>>> K. sort ()
>>> K
['A', 'Hello', 'World', 'z']
>>> T = map (lambda key :( key, d [key]), k)
>>> T
[('A', 1), ('hello', 10), ('World', 11), ('Z', 9)]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.