当前第2页 返回上一页
其中格式{key:[value1,value2,...]}
文本txt格式如下:
guaguashipinliaotianshi|.guagua.cn,
guaguashipinliaotianshi|iguagua.net,
guaguashipinliaotianshi|.17guagua.com,
jiuxiumeinvzhibo|.69xiu.com,
nbazhibo|.estream.cn,
youbo|yb.sxsapp.com,
其中第一列的名字有重复想要一个名字对应多个结果,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def makehostDict():
host_dict={}
f_allhost=open( 'xml_host.txt' , 'rb' )
lines=f_allhost.readlines()
for line in lines:
line_list=line.split( '|' )
name=line_list[0]
host=line_list[1].strip( '\n' )
if host is not '' :
if host_dict.has_key(name):
host_dict.get(name).append(host)#此处为关键向字典里已经有的key(name)值后继续添加value(host)
else :
host_dict.setdefault(name,[]).append(host)#创建{name,[host]}value为列表的格式的字典。
return host_dict
host_dict=makehostDict()
print host_dict
|
推荐教程:《python视频教程》
以上就是python字典中如何一键多值的写入?的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python如何判断整数
Python如何实现杨辉三角形 (代码)
Python识别图片中文字的方法
Python数据结构:一个被低估的namedtuple(一)
Python格式化输出是什么意思
Python可以写病毒吗
Python函数之chr(i)
关于Python中原始字符串与unicode字符串操作符的实例
Python字典一个键只能有一个值吗
详解Python中and和or的返回值
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python字典中如何一键多值的写入?