A Dictionary of Python learning

Source: Internet
Author: User
Tags shallow copy

Transferred from: http://blog.csdn.net/moodytong/article/details/7647684

In tuples and lists, the elements are accessed by numbers, but sometimes we access data by name or even data structures, and in C + + there is the concept of map, which is mapping, and in Python It also provides built-in mapping types-dictionaries. Mapping is actually a set of key and value and the mapping function between, it is characterized by: key uniqueness, key and value of a one-to-many mapping.

1. Creation of dictionaries

The basic form of a dictionary dic={key1:value1, key2:value2 ...}

Create Mode 1: direct type.

dict1={}

dict2={' name ': ' Earth ', ' Port ': ' 80 '}

Create Method 2: Use the Factory method Dict, through other mappings (such as dictionaries) or (keys, values) such a sequence to establish

items=[(' name ', ' Earth '), (' Port ', ' 80 ')]

Dict2=dict (items)

Dict1=dict ([' Name ', ' earth '],[' Port ', ' 80 '])

Create mode 3: Use the built-in method Fromkeys () to create a ' default ' dictionary in which the elements in the dictionary have the same value (if not given, the default is None)

Dict1={}.fromkeys ((' x ', ' Y '),-1)

#dict ={' x ':-1, ' Y ':-1}

Dict2={}.fromkeys (' x ', ' Y ')

#dict2 ={' x ': None, ' Y ': none}

2. Accessing values in the dictionary

The most common and basic is to use key to access value

A. Accessing the value's Get method via key

Dict1.get (' name ') #也可以直接是dictionary [' Key1 '], but when the key1 does not exist, an error is made, and a get returns none at this time

B. Random access to key value pairs

The dictionary is unordered, using the Popitem method is random popup a key value pair

C. Returning a list of all values in a dictionary

Method values

3. Accessing keys in the dictionary

A. Check if it contains Key1

Dictionary.has_key (Key1)

Key1 in Dictionarty

Key1 Not Dictionary

B. Returning a list of keys in a dictionary

Dictionary.keys ()

4. Access key-value pairs

A. Traversal mode

For R in Dicitonary #r是dictionary中的键值对

B. Modify (update) or add

Dictionary[key1]=value1

5. Delete

A. Press key to delete

Del Dictionary[key1]

B. Delete and return

Dictionary.pop (Key1)

C. Delete all items

Dictionary.clear ()

Del Dictionary

6. Sorting

Sorted (Dic.iteritems (), Key=lambda d:d[1], Reverse=false)

Description: The elements in the dictionary dic Follow D[1] (D[1] is value,d[0] is key, and D does not matter, can be changed to a or something) in ascending order, by setting the reverse true or false can be reversed, and returns the sorted dictionary (the sorted dictionary consists of tuples in the form [(key1,value1), (key2,value2),...], and the original dictionary remains the same)

7. Other

Len (dictionary) #返回字典项个数

Dictionary.item ()

Dictionary.iteritems ()

the method name Operation Dict.clear () removes all elements in the dictionary dict.copy () returns a copy of the dictionary (shallow copy) DICT.FROMKEYSC (Seq,val=None) creates and returns a new dictionary that is the key to the dictionary with the elements in the SEQ, and Val does the initial value corresponding to all the keys in the dictionary (default is None if this value is not provided) Dict.get (Key,default=None) returns the value of the key in the dictionary dict, if the key is not present in the dictionary, returns the value of default (note that the default value of the parameter is None) Dict.has_key (key) if the key (key) is in the word The code exists, returns TRUE, otherwise returns false. Introducing in and not on the Python2.2 versioninch, this method is almost obsolete, but still provides a working interface. Dict.items () Returns a list that contains a dictionary (key, value) to a tuple Dict.keys () returns a list containing the keys in the Dictionary dict.values () returns a list that contains all the values in the Dictionary Dict.iter () method iter Items (), Iterkeys (), itervalues () are the same as the non-iterative methods they correspond to, but they return an iteration instead of a list. Dict.pop (key[, default]) is similar to method get () If the key key exists in the dictionary, deletes and returns Dict[key], and throws a Keyerror exception if the key key does not exist and the value of default is not given. Dict.setdefault (Key,default=none) is similar to the method set (), if the key key is not present in the dictionary, the dict[key]=default assigns it a value. Dict.setdefault (Key,default=none) is similar to method set (), which is assigned by Dict[key]=default if the key key does not exist in the dictionary.

A Dictionary of Python learning

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.