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程序设计的学习有所帮助。

相关文章

使用pyinstaller打包PyQt4程序遇到的问题及解决方法

使用pyinstaller打包PyQt4程序遇到的问题及解决方法

python pyinstaller pyqt4 打包 QWindows 最近在做课设,用pyqt设计界面。然后用pyinstaller打包程序后,双击运行却总是闪退,后来将exe文件拖...

python隐藏类中属性的3种实现方法

python隐藏类中属性的3种实现方法

方法一: 效果图一: 代码一: # 定义一个矩形的类 class Rectangle: # 定义初始化方法 def __init__(self,width,height):...

探究Python多进程编程下线程之间变量的共享问题

 1、问题: 群中有同学贴了如下一段代码,问为何 list 最后打印的是空值?   from multiprocessing import Process, M...

pytorch 指定gpu训练与多gpu并行训练示例

一. 指定一个gpu训练的两种方法: 1.代码中指定 import torch torch.cuda.set_device(id) 2.终端中指定 CUDA_VISIBLE_DEV...

Python模块学习 re 正则表达式

re.match   re.match 尝试从字符串的开始匹配一个模式,如:下面的例子匹配第一个单词。 复制代码 代码如下: import re text = "JGood is a h...