Working with dictionaries in Python (add, delete, change, check)

Source: Internet
Author: User

A dictionary is another mutable container model, and can store any type of object, with the subscript starting at 0 and the last being-1.

Each key value of the dictionary (Key=>value) is split with a colon (:), each pair is separated by a comma (,), and the entire dictionary is enclosed in curly braces ({}) , as shown in the following format:

D = {key1:value1, key2:value2}

The key must be unique, but the value does not have to be, and the dictionary is unordered.

The value can take any data type, but the key must be immutable, such as a string, a number, or a tuple.

A simple Dictionary instance:

Dict = {'aaa' 'bb ' 882 ' ' CCC ' ' 2358 '}

You can also create a dictionary like this:

' DDD ': 1234'ddd': 1235, 98.6:37};
1. Increase
d[' height '] = 170
D.setdefault (' Age ', ' Max ') #显示d这个字典的 the content of ' age ' value, because the dictionary has, so will not go to set it
1 #Dictionary: Key-value, easy to value, fast, key cannot be repeated2D = {'name':'Nancy',3      ' Age':' -',4      'Sex':'female',5      'Addr':'NB'6      }7 #Increase8d['Height'] = 1709 Print(d)#{' sex ': ' Female ', ' age ': ' + ', ' name ': ' Nancy ', ' height ': ' addr ': ' NB '}Ten #dictionaries are unordered. OneValue = D.setdefault (' Age',' +')#Show D The contents of the ' age ' value of this dictionary, because the dictionary has, so does not go to set it A Print(value)# - -value1 = D.setdefault ('Weight', 98)##显示d这个字典的 ' weight ' value because the dictionary is not, so it's set to 98. - Print(value1)#98 the Print(d)#{' Height ': ", ' name ': ' Nancy ', ' age ': ' + ', ' addr ': ' nb ', ' sex ': ' female ', ' Weight ': 98}
2. Delete
D.pop (' height ') #删除某个key, this is more commonly used
D.popitem () # randomly deletes a
Del d[' name '] #删除某个key
D.clear () #清空字典
1 #Dictionary: Key-value, easy to value, fast, key cannot be repeated2D = {'name':'Nancy',3      ' Age':' -',4      'Sex':'female',5      'Addr':' China',6      'Height':' the'7      }8 #Delete9D.pop ('Height')#Delete a key, this is more commonly usedTen Print(d)#{' sex ': ' Female ', ' age ': ' + ', ' name ': ' Nancy ', ' addr ': ' China '} OneD.popitem ()#randomly deletes a A Print(d)#{' age ': ' + ', ' name ': ' Nancy ', ' addr ': ' China '} - deld['name']#Delete a key - Print(d)#{' sex ': ' Female ', ' addr ': ' China '} theD.clear ()#Empty Dictionary - Print(d)#{}
3. Modifications
d[' height '] = #如果key existing, modify its value, if it does not exist, add
1 #Dictionary: Key-value, easy to value, fast, key cannot be repeated2D = {'name':'Nancy',3      ' Age':' -',4      'Sex':'female',5      'Addr':' China',6      'Height':' the'7      }8 #Modify9d['Height'] = 170#If key exists, modify its value, if it does not exist, addTen Print(d)#{' addr ': ' China ', ' name ': ' Nancy ', ' height ': the ' age ': ' A ', ' sex ': ' Female '}
4. View

View by square brackets [] value

1 #Dictionary: Key-value, easy to value, fast, key cannot be repeated2D = {'name':'Nancy',3      ' Age':' -',4      'Sex':'female',5      'Addr':' China',6      'Height':' the'7      }8 #View9 Print(d['name'])#If you write a key that doesn't exist, you'll get an error, Nancy.Ten Print(d[' Age'])# -- One Print(D.get ('Addr'))# China A Print(D.get ('ADDR1'))#if get () is not there, return none, none - Print(D.get ('ADDR2','I can't find them .'))#- I can't find - Print(D.keys ())#get all Keys---Dict_keys ([' Age ', ' addr ', ' height ', ' name ', ' sex ') the Print(D.values ())#get all value---dict_values ([' + ', ' China ', ' + ', ' Nancy ', ' female ') - #d.has_key (' addr ') #python2 have this method inside, Python3 there is no - if 'Addr' inchD:#determine if key is in this dictionary -     Print('Addr')#Addr + #if ' addr ' in D.keys ():
1  forKinchD:#Take the key2     Print(k)#Print all the key values3 4 Print(D.items ())#is to turn the dictionary's key,value into a two-dimensional array (actually not really a two-dimensional array, to use the required cast), poor performance5 #- Dict_items ([' Height ', ' + '), (' Sex ', ' female ' ), (' Addr ', ' China '), (' Age ', ' "') ' (' Name ', ' Nancy ')])6res =list (D.items ())7 Print(Res[0])#(' height ', ' + ')8 9  forKvinchD.items ():#both key and value can be taken out at the same timeTen     Print(k,v) One #Height A #Sex Female - #Addr China - # Age the #name Nancy -  -  forKinchD:#good performance, preserving the original characteristics of the dictionary -     Print(K,d.get (k)) + # Height - #Sex Female + #Addr China A # Age at #name Nancy

Working with dictionaries in Python (add, delete, change, check)

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.