python字典循环赋值,Python字典循环添加一键多值的用法实例

python字典循环赋值,Python字典循环添加⼀键多值的⽤法实
循环写⼊字典key、value、删除指定的键值对:
空包弹助退器
原⽂本‘'每⾏元素以逗号分隔:
host_key,product_id,product_name,cont_start,cont_end
ah2.zhangyue,100002,掌阅,bookId=,&startChapterId
ih2.ireader,100002,掌阅,bid=,&
www.ireader,100002,掌阅,&bid=,&cid
m.zhangyue,100002,掌阅,readbook/,/
c13.shuqireader,100003,书旗,bookId=,&chapterId
t.shuqi,100003,书旗,bid/,/cid
想要得到:
{‘100002':‘product_name'.......}
代码如下:
def makeDict():
fileRead=open('','rb')
adlines()
read_dict={}#定义字典
for line in lines:
line_list=line.split(',')#每⾏按逗号分隔成列表
id=line_list[1]#取到id
name=line_list[2]#取到name智能平衡代步车
read_dict[id]=name#此处关键产⽣键值对,其中key是id
read_dict.pop('product_id')#删除key为‘product_id'的键值对
return read_dict
read_dict=makeDict()
循环写⼊⼀键对多值:
其中格式{key:[value1,value2,...]}
⽂本txt格式如下:
crpd-366guaguashipinliaotianshi|.guagua,
guaguashipinliaotianshi|iguagua,
guaguashipinliaotianshi|.17guagua,
jiuxiumeinvzhibo|.69xiu,
nbazhibo|.estream,
youbo|yb.sxsapp,
其中第⼀列的名字有重复想要⼀个名字对应多个结果,代码如下:
def makehostDict():
host_dict={}
灰板纸f_allhost=open('','rb')
lines=adlines()
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):
拖鞋生产设备
(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字典循环添加⼀键多值的⽤法实例就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持⼀教程⽹。

本文发布于:2024-09-21 22:17:59,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/1/159899.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:字典   循环   希望   想要   对应
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议