Python data structure (a) dictionary

Source: Internet
Author: User

0x 01 Dictionary Introduction

The child and list are the two most common data types in Python, the dictionary is the data type of the key-value pair (key-value) format, it has the same index as the list, but not the subscript in the list, but the key is used as the index, the value of the key is values, so the dictionary is unordered, So whenever you access a dictionary key, you can get the corresponding value. The key must be immutable and unique (as it is inherently de-weighed as set), such as strings, numbers, Ganso, and so on.


0x 02 The difference between a dictionary and other common data types

The data type symbol indicates whether the variable type (once the assignment is modifiable)

list [] mutable type

Ganso () immutable type

Collection {} mutable type

Dictionary {} mutable type


Here are some common things to do with dictionaries:


0x 03 Creation and addition of dictionaries

The simplest way to create a dictionary and add elements:

DIC = {} dic[' key1 '] = 1dic[' key2 '] = 2dic[' Key3 '] = 3


Directly print the dictionary name to see what the final dic dictionary data is:

Print (DIC) {' Key2 ': 2, ' Key1 ': 1, ' Key3 ': 3}


Above we created an empty dictionary called DiC, and added three Key:key1,key2,key3 to the dictionary, each key has a corresponding value, and the result of the final review proves that the dictionary store is unordered (no sequencing).


0x 04 removal of dictionaries

Dic.popitem () #调用字典的popitem () method, randomly deletes an element {' Key2 ': 2, ' Key3 ': 3}dic.pop (' Key2 ') #调用pop () method, deleting the specified key{' key1 ': 1, ' Key3 ' : 3}del dic[' Key3 '] #指定删除字典中的索引 (that is, key) and its value (value) {' Key1 ': 1, ' Key2 ': 2}


0x 05 Modification of the dictionary

dic[' Key2 ' = 4 #重新赋值即定义 {' Key1 ': 1, ' Key2 ': 4, ' Key3 ': 3}


0x 06 Dictionary Lookup

Print (dic[' Key2 ')) #直接使用key来寻找对应的值2print (dic[' Key4 ') #key方式直接读取, if the value corresponding to the key is not found, the Keyerror exception will be thrown keyerror: ' Key4 ' P Rint (Dic.get (' Key3 ')) #使用get () method, if the value exists, returns 3print (Dic.get (' Key4 ')) #get () method if the found value does not exist, a none object is returned, and a more friendly output noneprint ( Dic.setdefault (' Key3 ', ') ') #setdefault () method, if the specified key already exists, returns the current value of 3print (Dic.setdefault (' Key4 ', ' a ')) #如当前key不存在, Then set a default value to add to the dictionary and return value 44print (DIC) #最终的字典 {' Key3 ': 3, ' Key2 ': 2, ' Key1 ': 1, ' key4 ': ' 44 '}


Look at the difference between the keys (), the values (), the items () method in the dictionary:

[Print (i) for I in Dic.keys ()] #可以看到keys () stores the dictionary key (the name of the key) Key1key3key2[print (i) for I in Dic.values ()] #values () stores all Values (value) 132[print (k,v) for k,v in Dic.items ()] #而items () is the value () of the key and key corresponding to the values () Key1 1key3 3key2 2


0x 07 Use of dictionaries (i)

"" "is implemented using a dictionary: the user enters a number, prints each digit and the number of repetitions" "" #  determines whether the user input is a digital print (' [note] please input a  Integer. ') While true:    num = input (' >>>  '). Strip (). Lstrip (' 0 ')      if num.isdigit ():        break     else:        print (' [Error] you input is  not a number, please re-input. ') #空字典nums  = {} #value值递增for  i in num:    if not nums.get ( i):   #返回key对应的值value         nums.setdefault (i, 1)      else:        print (Nums.get (i))          nums[i] += 1# iterative Output for k, v in nums.items ():    #keys ()    values ()     items () &NBsp;   print (K, V) 


0x 08 use of dictionaries (ii)

"" "The number repeats randomly produces a range of 100 integer numbers [ -1000,1000] to output all the different numbers and their repetitions in ascending order" "" "Import Randomnums = {}for _ in range: Randnum s = Random.randrange ( -1000, +) if Nums.get (randnums): nums[randnums] + = 1 Continue Else:num S.setdefault (randnums, 1) keys = sorted (Nums.keys ()) for I in Keys:print (' {: <4} {: <4} '. Format (i, nums[i]))




0x 09 dictionary use (c)

"" "String repetition statistics      character chart ' abcdefghijklmnopqrstuvwxyz '      randomly selects 2 letters to form a string, a total of 100 selected      descending output of these 100 strings and the number of repetitions "" "" import randomimport stringstrs =  " ABCDEFGHIJKLMNOPQRSTUVWXYZ ' Dic = {}for _ in range (+):     #  randstr =  ". Join (Random.sample (strs, 2))     randstr = " ". Join (Random.choice (STRs)  for _ in range (0, 2))     #三种输出2个随机字符的方式      # randstr =  ". Join (Random.sample (string.ascii_lowercase, 2))      if randstr not in dic:         Dic.setdefault (randstr, 1)     else:         Dic[randstr] += 1sortstr = sorted (Dic.keys ())     #升序 #sortstr =  Sorted (Dic.keys (), reverse=true) &NBSP;&NBSP; #降序for  i in sortstr:    print (' {: <4} {:<4} '. Format (i,  Dic[i]) "" "data     #string模块的一些常用字符串对象            __all__ = [' ascii_letters ',  ' ascii_lowercase ',  ' ascii_uppercase ',  ' Capwords ',  ' digits ',  ' hexdigits ',  ' octdigits ', ',  ' printable ',  ' punctuation ',  ' Whitespace ',  ' Formatter ',  ' Template ']ascii_letters =  ' Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ' ascii_lowercase =  ' abcdefghijklmnopqrstuvwxyz ' ascii_uppercase =  ' abcdefghijklmnopqrstuvwxyz ' digits =  ' 0123456789 ' hexdigits =  ' 0123456789abcdefABCDEF ' octdigits =  ' 01234567 ' printable =  ' 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz! " #$%&\ ' () *+,-./:;<=>[email protected][\\]^_ ' {|} ~ \t\n\r\x0b\x0c ' punctuation =  '! " #$%&\ ' () *+,-./:;<=>[eMail protected][\\]^_ ' {|} ~ ' whitespace =  '  \t\n\r\x0b\x0c ' "" "





Python data structure (a) dictionary

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.