Python dictionary (Array) Action sort of learning notes

Source: Internet
Author: User
Tags function definition shallow copy


A dictionary is the most similar sequence structure to a PHP array. The list of Python can only be a sequence that starts with an indexed number and increments sequentially. A dictionary can be a sequence of letters as key.

Tuples are generally expressed in parentheses, such as (1,2,3)
Lists are generally expressed in square brackets, such as [1,2,3]
The dictionary (dict) is represented by curly braces, such as {' A ': 1, ' B ': 2, ' C ': 3}

Unlike PHP, PHP's key,value are represented by Key=>value, and Python is separated by a colon ":".

Dictionaries can use curly braces to write keys and values or use the Dict function to create them.
The Dict function can specify two tuples or lists to correspond to the creation of a dictionary. Such as:

Items = [(' Name ', ' Gumby '), (' Age ', ' 42 ')]
D = dict (items)

The difference from the list:

K in D (d is a dictionary), looking for a key instead of value, and the expression V in L (L is a list) is used to find the value, not the index.

Some dictionary methods:

Clear clears the dictionary. "In-place operation" does not return a value, similar to the list's Sort method
The Copy method returns a new dictionary of the same key-value pairs. Shallow copy. Because the value itself is the same, not the replica.
When you replace a value in a replica, the original dictionary is unaffected. But if you modify a value, the original dictionary changes. One way to avoid this problem is to use deep copy (deep copy).

From copy import deepcopy
Deepcopy (d)

The D.fromkes method creates a new dictionary with the given value. The default for each key corresponds to none
The Get method gets a nonexistent key without an error and returns none
Has_key method Phase method in expression K-D
The items method returns all the alphabetic items as a list. Each of these lists comes from (the key, the value). However, items do not have a special order when they are returned.
The Iteritmes method is roughly the same, but returns an iterator object instead of a list. In many cases iteritems efficiency is higher. An iterator, which is equivalent to an object after decode JSON, rather than an array,
The Keys method returns the key in the dictionary as a list. Iterkeys, however, returns an iterator for the key.
Pop pops up the value of the given key. Popitem pops up the last element (actually a random item), but if you want to remove and process the dictionary one after another, the popitem is much more efficient because you don't have to get a list of the dictionary's key values first.

Values and Itervalues methods return a value in a dictionary as a list or iterator, and the list of returned values can contain duplicates.

Look at some examples of Python dictionary operations

Suppose the dictionary is dics = {0: ' A ', 1: ' B ', ' C ': 3}

1. Take the value from the dictionary, when the key does not exist do not want to handle the exception

[Method] Dics.get (' key ', ' not found ')

e.g.

[Explain] when the key ' key ' does not exist, print ' not found ' (that is, the information you want to process), when there is the output key value.

"Other Solution One"

if  in dics:     
     Print Dics[key] 
 Else :     
     Print ' Not found!! '

"Other Solution II"

Try :    
      Print Dics[key] 
 except keyerror:    
      Print ' Not found '

Example:

2. Take the value from the dictionary, if found, delete; Do not want to handle an exception when the key does not exist

[Method] Dics.pop (' key ', ' not found ')

e.g.

[Explain] when the key ' key ' does not exist, print ' not found ' (that is, the information you want to process), when there is the output key value, and remove the health.

3. Add an entry to the dictionary. If it does not exist, specify a specific value;

[Method] Dic.setdefault (key, default)

e.g.

Python dictionary sorting

DIC = {' A ': 3, ' B ': 2, ' C ': 1}
Attention
After sorting the original dictionary has not changed, the order is still
Two functions
1.lambda
Functions: Creating anonymous functions
Difference: and def function definition, following two points difference
    • A lambda creates a function object , but does not assign the function object to an identifier, and Def assigns the function object to a variable
    • Lambda It's just an expression, and DEF is a statement
Case:
2.iteritems ()
Function: Iteritems () returns the dictionary key value pair with the iterator object
Difference: Items are returned as a list in the form of a dictionary key value pair
Case:
Note: in function sorted (Dic.iteritems (), key = Lambda asd:asd[1]), the first argument is passed to the second argument "key-key value", the second parameter takes out the key ([0]) or the key value (1))
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.