Python dictionary, python

Source: Internet
Author: User

Python dictionary, python
This article mainly introduces the dictionary in python, which is one of the most powerful data types in Python, this article explains what is a dictionary, how to create a dictionary and assign values to the dictionary, basic operations on the dictionary, ing type operators, ing related functions, and dictionary methods. For more information, see

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 the Code 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 the Code 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 the Code 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 the Code as follows:
For key in adict. keys (): print key


2. traverse the dictionary value (value)

Copy the Code as follows:
For value in adict. values (): print value


3. Traverse dictionary items (elements)

Copy the Code as follows:
For item in adict. items (): print item


4. traverse the dictionary's key-value

Copy the Code 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.

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.