黑松山资源网 Design By www.paidiu.com
循环写入字典key、value、删除指定的键值对:
原文本‘jp_url.txt'每行元素以逗号分隔:
host_key,product_id,product_name,cont_start,cont_end ah2.zhangyue.com,100002,掌阅,bookId=,&startChapterId ih2.ireader.com,100002,掌阅,bid=,& www.ireader.com,100002,掌阅,&bid=,&cid m.zhangyue.com,100002,掌阅,readbook/,/ c13.shuqireader.com,100003,书旗,bookId=,&chapterId t.shuqi.com,100003,书旗,bid/,/cid
想要得到:
{‘100002':‘product_name'.......}
代码如下:
def makeDict(): fileRead=open('jp_url.txt','rb') lines=fileRead.readlines() 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格式如下:
guaguashipinliaotianshi|.guagua.cn, guaguashipinliaotianshi|iguagua.net, guaguashipinliaotianshi|.17guagua.com, jiuxiumeinvzhibo|.69xiu.com, nbazhibo|.estream.cn, youbo|yb.sxsapp.com,
其中第一列的名字有重复想要一个名字对应多个结果,代码如下:
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字典循环添加一键多值的用法实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月07日
2024年10月07日
- 群星.1991-音乐工厂1·皇后大道东【音乐工厂】【WAV+CUE】
- 群星.1992-音乐工厂2·首都【音乐工厂】【WAV+CUE】
- 群星.1994-音乐工厂3·儿童乐园【音乐工厂】【WAV+CUE】
- 胡鸿钧.2021-ex:CHANGE【星梦娱乐】【WAV+CUE】
- 班得瑞原装进口《第一张新世纪专辑:仙境》1CD[APE/CUE分轨][292.3MB]
- 伍佰《摇滚教父 伍佰黄金精选 2CD》[WAV+CUE][990MB]
- 班得瑞原装进口《第二张新世纪专辑:寂静山林》1CD[APE/CUE分轨][327.1MB]
- Beyond.1989-真的见证(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 陈怡婷.2024-予你的心谁来赔【福茂】【FLAC分轨】
- 陈冠希.2003-HITS.OR.MISSES【英皇娱乐】【WAV+CUE】
- 班得瑞原装进口《第三张新世纪专辑:春野》1CD[APE/CUE分轨][278.9MB]
- 班得瑞原装进口《第四张新世纪专辑:蓝色天际》1CD[APE/CUE分轨][284.8MB]
- 班得瑞原装进口《第五张新世纪专辑:迷雾森林+EP》1CD[APE/CUE分轨][334.2MB]
- 田震.1997-顺其自然(日版)【红星生产社】【WAV+CUE】
- 小虫.1996-想得太美【滚石】【WAV+CUE】