Basic Python Tutorial "reading notes"-2016/7/19

Source: Internet
Author: User
Tags shallow copy

Hope to continue to update through the blog park, share and record the basic knowledge of Python to the advanced application of the dots drop!

Eighth wave: Chapter 4th Dictionary: When indexing is not good

  You will learn a data structure that refers to a value by name, which is called a mapping mapping. The dictionary is the only built-in mapping type within Python. The values in the dictionary are not in a special order and are stored in a specific key. Keys to make numbers, strings, or even tuples.

[4.1] Use of dictionaries

  Dictionaries are sometimes more used than lists.

[4.2] Creating and using dictionaries

    A dictionary consists of pairs of keys and their corresponding values (also referred to as key/value pairs). Each key and its value are separated by a colon, and the items are separated by commas, and the entire dictionary is surrounded by a bunch of curly braces. The keys in the dictionary are unique, and the values are not unique.

[4.2.1] dict function

Use the Dict function to enter a CV dictionary through other mappings or sequence of key values.

[4.2.2] Basic dictionary operation

Len (d) Returns the number of items in D

D[K] Returns the value associated to the key K

D[K]=V associates the value V to the key K

Del D[k] Delete item with key K

K in D checks if D contains an entry with a key of K

Although dictionaries and lists have the same multiple attributes, there are some important differences.

  Key type: The key of a dictionary is not necessarily an integer or other immutable type, such as a floating-point, string, or tuple

  Auto Add: You can assign a value to a key even if it doesn't exist in the dictionary at the beginning of the period.

  Membership:K in D looks for a key, not a value. Checking the membership of a key in a dictionary is more efficient than checking the membership in the list, the larger the size of the data structure, the more obvious the efficiency gap between the two.

formatted string for [4.2.3] Dictionary

[4.2.4] Dictionary method

1. Clear

The clear method clears all items in the dictionary. This is a in-place operation (similar to list.sort), so no return value (or none) is returned. If you really want to empty all the elements in the original dictionary, you must use the Clear method.

2. Copy

The Copy method returns a new dictionary with the same key-value pair (this method implements a shallow assignment of shallow copy) because the value itself is the same, not a copy.

x={' username ': ' admin ', ' machines ': [' foo ', ' Bar ', ' Baz ']}

Y=x.copy ()

y[' username ']= ' MLH '

y[' Machines '].remove (' bar ')

>>>y

{' username ': ' MLH ', ' Machines ': [' foo ', ' Bar ']}

>>>x

{' username ': ' admin ', ' machines ': [' foo ', ' Bar ']}

The original dictionary is not affected when the value is replaced in the copy. However, if you modify a value (modify it in place, instead of replacing it), the original dictionary also changes because the same value is stored in the original dictionary.

One way to avoid this problem is to use deep copy, which contains all the values. You can use the Deepcopy function of the copy module to complete the operation:

From copy import deepcopy

3. Fromkeys

The Fromkeys method creates a new dictionary with the given key, and each key defaults to a value of none.

Dict.fromkeys ([' Name ', ' age '])

Dict.fromkeys ([' Name ', ' age '], ' (Unknown) ') #不使用None作为默认值, provide default values for yourself

4. Get

The Get method is a more permissive way to access dictionary items. When you use get to access a nonexistent key, there is no exception, and the value of none is obtained. You can also customize the "default" value, replacing None:d.get (' name ', ' N/A ')

5. Has_key

The Has_key method can check whether the dictionary contains the given key.

6. Items and Iteritems

The items method returns all dictionary entries in a list, each of which comes from a key-value pair. And the items are returned with no special order.

The Iteritems method works roughly the same, but returns an iterator object instead of a list. In many cases, using iteritems is more efficient, especially if you want to iterate over the results.

7. Keys and Iterkeys

The Keys method returns the keys in the dictionary as a list, and Iterkeys returns an iterator for the key.

8. Pop

The Pop method is used to get the value corresponding to the given key, and then the key-value pair is removed from the dictionary.

9. Popitem

The Popitem method is similar to List.pop, which pops up the last element of the list. But the difference is that popitem pops up random entries because the dictionary does not have "last element" or other concepts about the order. This method works well if you want to remove and process items one after the other, because you don't have to get the list of keys first.

The dictionary does not have a method equivalent to append, because the dictionary is unordered, and a method similar to append is meaningless.

Ten. SetDefault

The SetDefault method is somewhat similar to the Get method, which is the ability to get the value associated with a given key, and in addition, SetDefault can set the corresponding key value without the given key in the dictionary.

One. Update

The Update method can update another dictionary with one dictionary item. The items in the provided dictionary are added to the old dictionary and overwritten if the same key is available.

Values and Itervalues

The values method returns the value in the dictionary as a list, itervalues the iterator that returns the value. Unlike a list of returned keys, a list of returned values can contain duplicate elements.

[4.3] Summary

mapping: mappings can use any immutable object to identify elements. Python's only built-in mapping type is a dictionary.

format a string with a dictionary: apply character formatting to the dictionary by including the name (key) in the format specifier.

Dictionary Method: The method that is called is the same as the invocation list and the string method.

Basic Python Tutorial "reading notes"-2016/7/19

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.