Python implements methods for adding entries to dictionaries

  • 2020-04-02 14:06:56
  • OfStack

This article illustrates how python implementations add entries to dictionaries, a practical tip for dictionary operations. Share with you for your reference.

The specific implementation method is as follows:


def addWord(theIndex,word,pagenumber): 
  theIndex.setdefault(word, [ ]).append(pagenumber)# Existing on the basis of the addition of the list, does not exist on a new dictionary key 
 
d = {"hello":[3]} 
#d = {} 
addWord(d,"hello",3) 
addWord(d,"hello",56) 
addWord(d,"nihao",24) 
print d 

The test environment for this article is Python2.7.6

The results of the program are as follows:


{'nihao': [24], 'hello': [3, 3, 56]}

I hope that this article has helped you to learn Python programming.


Related articles: