python实现给字典添加条目的方法

yipeiwu_com6年前Python基础

本文实例讲述了python实现给字典添加条目的方法,是针对字典操作中比较实用的技巧。分享给大家供大家参考。

具体实现方法如下:

def addWord(theIndex,word,pagenumber): 
  theIndex.setdefault(word, [ ]).append(pagenumber)#存在就在基础上加入列表,不存在就新建个字典key 
 
d = {"hello":[3]} 
#d = {} 
addWord(d,"hello",3) 
addWord(d,"hello",56) 
addWord(d,"nihao",24) 
print d 

本文测试环境为Python2.7.6

程序运行结果如下:

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

希望本文所述对大家Python程序设计的学习有所帮助。

相关文章

Python 获取 datax 执行结果保存到数据库的方法

执行 datax 作业,创建执行文件,在 crontab 中每天1点(下面有关系)执行: 其中 job_start 及 job_finish 这两行记录是自己添加的,为了方便识别出哪张表...

python读写Excel表格的实例代码(简单实用)

python读写Excel表格的实例代码(简单实用)

安装两个库:pip install xlrd、pip install xlwt 1.python读excel——xlrd 2.python写excel——xlwt 1.读excel数据,...

Python中zfill()方法的使用教程

 zfill()方法用零垫串来填充左边宽度。 语法 以下是zfill()方法的语法: str.zfill(width) 参数    ...

Python实现根据IP地址和子网掩码算出网段的方法

本文实例讲述了Python实现根据IP地址和子网掩码算出网段的方法。分享给大家供大家参考。具体如下: 该代码在Linux环境2.6.6python版本测试通过! #!/usr/bin...

python设定并获取socket超时时间的方法

python写法 import socket def test_socket_timeout(): s = socket.socket(socket.AF_INET,...