Python's Dict Dictionary

Source: Internet
Author: User
Tags shallow copy

Python has built-in dictionaries: dict support, Dict full name dictionary, also known as map in other languages, dictionaries are another mutable container model and can store any type of object. Has a very fast search speed.

A dictionary is a data structure referenced by a name or keyword, which can be a number, a string, a tuple, and this type of structure is also known as a mapping. The dictionary type is the only built-in mapping type in Python, and the basic operations include the following:

(1) Len (): Returns the number of keys in the dictionary: value pairs

(2) D[k]: Returns the value corresponding to the keyword;

(3) D[k] = V: Associates the value to the key value K;

(4) del d[k]: Delete the key value of K;

(5) Key in D: Key value key is in D, returns true, otherwise false

Example Dictionary:
D = {    "k1": "    K2": True, "    K3": [' Su ', {        ' kk1 ': ' Vv1 ', ' kk2 ': ' Vv2 ', ' KK3 ':        (one, one        ),    }
   ],    "K4": (11, 22, 33, 44)}

  

1. The basic format of the dictionary:
D = {key1:value1, key2:value2}
2. The key of the dictionary must be immutable (for example: string, number, tuple), value (key) can be any data type
D1 = {' Alice ': ' 2341 ', 9102: ' Bibi ', (11,22): ' 3258 '} # Correct
D2 = {[' Alice ', 123]: ' 2341 ', True: ' 9102 ', {' abc ': ' 123 ', ' EFG ': ' 456 '}} # Error! Because the list Boolean dictionary is mutable, it cannot be used as a key

3. The dictionary is unordered, and each time the print is executed, the order will change.
D3 = {' Alice ': ' 2341 ', 9102: ' Bibi ', (11,22): ' 3258 '}print (d) # The print result may be this {' Alice ': ' 2341 ', 9102: ' Bibi ', (11, 22): ' 3258 '}# It may also be so {(one, All): ' 3258 ', ' Alice ': ' 2341 ', 9102: ' Bibi '}# may even be so {9102: ' Bibi ', ' Alice ': ' 2341 ', (11, 22): ' 3258 '} ...

 

4. Check out the corresponding value (value) or key (key) & for loop based on key (key) or values (value)

1. Return the value corresponding to the keyword: v = D[key] Example (refer to the top example dictionary):

v = d["K1"] # remove K1 corresponding value
V1 = d["K3"][1]["Kk3"][0] # Take out the KK3 corresponding to the value of 11

Print (V, v1)

2. The key-value pair cannot be obtained by slicing because the dictionary is unordered

3.for loop takes key and value

D4 = {' Year ': 2018, ' Month ': 3, ' Day ': 18}# loops all key (or so write: for item in D4.keys ():) for item in D4:        print (item) printing result: Year monthday# Loop all Valuefor item in D4.values ():        print (item) Results: 2018318# loop all Key:valuefor item in D4.keys ():    Print (item, ': ', D4[item])
For K, V in D4.items (): # receives key with the items method K, V receives value
Print (k, v)

  

5. Functions & Methods of dictionaries 1. Functions (3):

1.str (dict) #输出字典可以打印的字符串表示

d6 = {' Year ': 2018, ' month ': 3, ' day ': 18}content = str (d6) print (content) results: {' Year ': 2018, ' month ': 3, ' Day ': 18}

2.len (dict) #计算字典内元素的个人, that is, the total number of keys

D7 = {' Year ': 2018, ' Month ': 3, ' day ': 18}count = Len (d7) print (count) results: 3

3.type (variable) #返回输入的变量类型, returns a dictionary if the variable type is a dictionary

D8 = {' Year ': 2018, ' Month ': 3, ' day ': 18}ty = Type (d8) print (Ty) printing results: <class ' dict ' >

  

2. Method ()

1. Delete

D4 = {' Alice ': ' 2341 ', 9102: ' Bibi ', (11,22): ' 3258 '}del d4[9102]    # Delete element 9102:bibiprint (d4)       # Print Result: {' Alice ': ' 2341 ', (one, All): ' 3258 '} d4.clear () # Empty the dictionary print (D4)       # Print Result: {}del d4  # Delete Dictionary

2.items

D4 = {' Year ': 2018, ' Month ': 3, ' Day ': 18}for K, V in D4.items (): # receives key with the items method K, V receives value    print (k, v)

3.keys

D4 = {' Year ': 2018, ' Month ': 3, ' Day ': 18}for item in D4.keys ():    # loop all key    print (item)

4.values

D4 = {' Year ': 2018, ' Month ': 3, ' Day ': 18}for item in D4.values ():  # loop All values      print (item)

5.copy (Shallow copy)

D4 = {' Year ': 2018, ' Month ': 3, ' Day ': $ dict2 = D4.copy () print ("Newly copied dictionary:", Dict2)

6.fromkeys () Creates a new dictionary with the key to the dictionary of the elements in the sequence seq, and Val is the initial value corresponding to all the keys in the dictionary

Seq = (' year ', ' Month ', ' Day ') Dict1 = Dict.fromkeys (seq) print ("New dictionary:%s"% str (dict1)) Dict1 = Dict1.fromkeys (seq, 8) Print ("New dictionary:%s"% str (DICT1)) # Output: # New dictionary: {' year ': None, ' month ': None, ' Day ': none}# new dictionary: {' Year ': 8, ' month ': 8, ' Day ' : 8}

  

 

 

 

Python's Dict Dictionary

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.