Python Dictionary (reproduced)

Source: Internet
Author: User
Tags delete key shallow copy

First, what is a dictionary

A dictionary is the only type of mapping in the Python language.

A hash value (key, key) and a pointer to an object (values, value) are a one-to-many relationship that is often considered a mutable hash table in the mapping type object.

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

The difference between a dictionary type and a sequence type:

1. Access to and access to data differs in different ways.
2. The sequence type only uses the key of the numeric type (indexed in numerical order from the beginning of the sequence);
3. The mapping type can be used as a key for other object types (e.g. numbers, strings, ganso, usually strings as keys), and the keys of the sequence type are different, the key of the mapping type is straight

4. Connect to or indirectly associate with the stored data value.

5. The data in the mapping type is unordered. This is not the same as the sequence type, and the sequence type is numerically ordered.

6. The mapping type is directly "mapped" to a value with a key.

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

The key must be immutable, so it can be used as a number, string, or tuple, so the list doesn't work.

Ii. creating dictionaries and assigning values to dictionaries

In a nutshell, a dictionary is a collection of key-value pairs wrapped in curly braces. (Key-value pairs are also referred to as items)
General form:

The code is as follows:

Adict = {}

Adict = {key1:value2, key2:value2, ...}

Characteristics:

1). Key and value separated by colon ":";

2). The items and items are separated by commas ",";

3). The keys in the dictionary must be unique, and the values may not be unique.

The code is as follows:

adict = {' name ': ' Allen ', ' name ': ' Lucy ', ' Age ': ' 40′} with 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 form, such as: ' Age ': ' 040′ instead of ' age ': 040

Iii. basic operation of the dictionary

1. Accessing values in the dictionary

Adict[key] Returns the value of key key, if key is not in the dictionary, a keyerror is raised.

2. Check if key is in the dictionary

In, no in shape such as: ' Name ' in adict with –>true, no –>false

3. Updating dictionaries

A, add a data item (new Element) or key-value pair

Adict[new_key] = value form adds an item

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 key key item/del adict delete entire dictionary

Adict.pop (key) deletes the key keys and returns the value corresponding to key

Iv. mapping-related functions

1, Len () returns the length of the dictionary

Bdict = {' name ': 'test ',' age ':'+ '}
Print (len (bdict))

2, hash () returns the hash value of the object, which can be used to determine whether an object can be used as a dictionary key

Print (hash (' a '))
Results: 5439121936382221501

3, Dict () Create a dictionary

Vi. Methods of the dictionary

1, Adict.keys () returns a list containing all keys of the dictionary;

2, Adict.values () returns a list containing all the value of the dictionary;

3, Adict.items () returns a list containing all (key, value) Ganso;

4, adict.clear () Delete all the items or elements in the dictionary;

5, Adict.copy () returns a copy of a shallow copy of a dictionary;

6, Adict.fromkeys (seq, val=none) creates and returns a new dictionary, with the element in SEQ making the dictionary key, and Val does the initial value corresponding to all the keys in the dictionary (default is None);

Seq = (' A ',' B ',' C ')
Print (type (seq))
Cdict = Bdict.fromkeys (seq,10)
Print (cdict)
Result: {' A ': ten, ' C ': Ten, ' B ': 10}

7, Adict.get (key, default = None) returns the value corresponding to the key in the dictionary, and returns the value of default if the key does not exist in the dictionary (default defaults to none);

Print (Bdict.get (' name ',' None '))
Print "Value:%s"% dict.get (' Sex ', "never")

9, Adict.iteritems (), Adict.iterkeys (), Adict.itervalues () and their corresponding non-iterative methods, the difference is that they return an iteration, rather than 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 key corresponding to the Vuale; if the key does not exist and the default value is not given, the keyerror exception is thrown;
11, Adict.setdefault (key, Default=none) and set () method similar, but if the dictionary does not exist in the key key, by adict[key] = default for it assignment;
12, Adict.update (bdict) adds the dictionary bdict key-value pairs to the dictionary adict.

Vii. the traversal of a dictionary

1. Traverse the dictionary key (key)

The code is as follows:

For key in Adict.keys ():p rint key

2. The value of the traversal dictionary

Copy the Code code as follows:

For value in Adict.values (): Print value

3. Traversing dictionary entries (elements)

Copy the Code code as follows:

For item in Adict.items ():p rint Item

4, traverse the dictionary Key-value

Copy the Code code as follows:

For Item,value Inadict.items (): print ' key=%s, value=%s '% (item, value) or for Item,value inadict.iteritems (): print ' Ke y=%s, value=%s '% (item, value)

Note: for Item,value inadict.items (): print ' key=%s ', ' value=%s ',% (item, value) This notation is wrong

Viii. Considerations for using dictionaries

1, can not allow a key to correspond to multiple values;

2, the key must be hashed.

Python Dictionary (reproduced)

Related Article

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.