[Python] python常用字典操作范例 →→→→→进入此内容的聊天室

来自 , 2021-03-08, 写在 Python, 查看 100 次.
URL http://www.code666.cn/view/125b93c9
  1. # experimenting with the Python dictionary
  2. # a seemingly unordered set of key:value pairs, types can be mixed
  3. # Python23 tested     vegaseat     13feb2005
  4. # initialize a dictionary, here a dictionary of roman numerals
  5. romanD = {'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8,'IX':9}
  6. print "A dictionary is an unordered set of key:value pairs:"
  7. print romanD
  8. # create an empty dictionary
  9. D1 = {}
  10. # show empty dictionary contents and length (number of item/pairs)
  11. print "Empty Dictionary contains:"
  12. # shows  {}
  13. print D1
  14. # shows Length = 0
  15. print "Length = ", len(D1)
  16. # add/load new key:value pairs by using indexing and assignment
  17. # here 'eins' is the key, 'one' is the key value
  18. # the start of a german to english dictionary
  19. D1['null'] = 'zero'
  20. D1['eins'] = 'one'
  21. D1['zwei'] = 'two'
  22. D1['drei'] = 'three'
  23. D1['vier'] = 'four'
  24. # print loaded dictionary and length
  25. # the dictionary key order allows for most efficient searching
  26. print "Dictionary now contains (notice the seemingly random order of pairs):"
  27. print D1
  28. print "Length = ",len(D1)
  29. # find the value by key (does not change dictionary)
  30. print "The english word for drei is ", D1['drei']
  31. # better
  32. if 'drei' in D1:
  33.     print "The english word for drei is ", D1['drei']
  34. # create a list of the values in the dictionary
  35. L1 = D1.values()
  36. # the list can be sorted, the dictionary itself cannot
  37. L1.sort()
  38. print "A list of values in the dictionary (sorted):"
  39. print L1
  40. # create a list of dictionary keys
  41. L2 = D1.keys()
  42. L2.sort()
  43. print "A list of the dictionary keys (sorted):"
  44. print L2
  45. # does the dictionary contain a certain key?
  46. if D1.has_key('null'):
  47.     print "Key 'null' found!"
  48. else:
  49.     print "Key 'null' not found!"
  50. # copy dictionary D1 to D2 (the order may not be the same)
  51. D2 = D1.copy()
  52. print "Dictionary D1 has been copied to D2:"
  53. print D2
  54. # delete an entry
  55. del D2['zwei']
  56. print "Dictionary D2 after 'zwei' has been deleted:"
  57. print D2
  58. # extract the value and remove the entry
  59. # pop() changes the dictionary, use e3 = D2['drei'] for no change
  60. e3 = D2.pop('drei')
  61. print "Extract value for key = 'drei' and delete item from dictionary:"
  62. print e3
  63. print "Dictionary D2 after 'drei' has been popped:"
  64. print D2
  65. print
  66. str1 = "I still miss you baby, but my aim's gettin' better!"
  67. print str1
  68. print "Count the characters in the above string:"
  69. # create an empty dictionary
  70. charCount = {}
  71. for char in str1:
  72.     charCount[char] = charCount.get(char, 0) + 1
  73. print charCount
  74. print
  75. if 't' in charCount:
  76.     print "There are %d 't' in the string" % charCount['t']
  77. print
  78. str2 = "It has been a rough day. I got up this morning put on a shirt and a"
  79. str2 = str2 + " button fell off. I picked up my briefcase and the handle came off."
  80. str2 = str2 + " Now I am afraid to go to the bathroom."
  81. print str2
  82. print "Count the words in the above string, all words lower case:"
  83. # create a list of the words
  84. wordList = str2.split(None)
  85. # create an empty dictionary
  86. wordCount = {}
  87. for word in wordList:
  88.     # convert to all lower case
  89.     word = word.lower()
  90.     # strip off any trailing period, if needed do other punctuations
  91.     if '.' in word:
  92.         word = word.rstrip('.')
  93.     # load key:value pairs by using indexing and assignment
  94.     wordCount[word] = wordCount.get(word, 0) + 1
  95. print wordCount
  96. print
  97. # put keys into list and sort
  98. keyList = wordCount.keys()
  99. keyList.sort()
  100. # display words and associated count in alphabetical order
  101. for keyword in keyList:
  102.     print keyword, "=", wordCount[keyword]
  103. # put the dictionary pairs into a list, use the romanD dictionary
  104. romanList = []
  105. for key, value in romanD.items():
  106.     # put value first for a meaningful sort
  107.     romanList.append((value, key))
  108. romanList.sort()
  109. print "\nThe roman numeral dictionary put into a (value,pair) list then sorted:"
  110. print romanList
  111. print "\nList them as pairs on a line:"
  112. for i in xrange(len(romanList)):
  113.     print romanList[i][0],'=', romanList[i][1]
  114. print
  115. # split the romanD dictionary into two lists
  116. print "Splitting the romanD dictionary into two lists:"
  117. romankeyList = []
  118. romanvalueList = []
  119. for key, value in romanD.items():
  120.     romankeyList.append(key)
  121.     romanvalueList.append(value)
  122. print "Key List:",romankeyList
  123. print "Value List:",romanvalueList
  124. print
  125. # make a dictionary from the two lists
  126. print "Combining the two lists into a dictionary:"
  127. romanD1 = dict(zip(romankeyList, romanvalueList))
  128. print romanD1
  129. # to save a Python object like a dictionary to a file
  130. # and load it back intact you have to use the pickle module
  131. import pickle
  132. print "The original dictionary:"
  133. print romanD1
  134. file = open("roman1.dat", "w")
  135. pickle.dump(romanD1, file)
  136. file.close()
  137. file = open("roman1.dat", "r")
  138. romanD2 = pickle.load(file)
  139. file.close()
  140. print "Dictionary after pickle.dump() and pickle.load():"
  141. print romanD2
  142. print
  143. # let's get rid of some duplicate words
  144. str = "Senator Strom Thurmond dressed as as Tarzan"
  145. print "\nOriginal string:"
  146. print str
  147. print "A list of the words in the string:"
  148. wrdList1 = str.split()
  149. print wrdList1
  150. def uniqueList(anyList):
  151.     """given a list, returns a unique list with the order retained"""
  152.     # create an empty dictionary
  153.     dic1 = {}
  154.     # use a list comprehension statement and the unique feature of a dictionary
  155.     return [dic1.setdefault(e,e) for e in anyList if e not in dic1]
  156. # a call to the above function will retain the order of words
  157. wrdList2 = uniqueList(wrdList1)
  158. print "Convert unique list back to string (order retained):"
  159. print " ".join(wrdList2)
  160. #//python/5731

回复 "python常用字典操作范例"

这儿你可以回复上面这条便签

captcha