Python字典循环添加一键多值的用法实例
作者:风中摇曳的叶子 时间:2021-07-15 14:48:48
循环写入字典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
来源:https://blog.csdn.net/a1084958096/article/details/78375563
标签:Python,字典,一键,多值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现随机森林回归与各自变量重要性分析与排序
2023-05-04 05:52:21
![](https://img.aspxhome.com/file/2023/0/69580_0s.png)
pytorch Dropout过拟合的操作
2023-11-26 16:12:18
![](https://img.aspxhome.com/file/2023/7/80607_0s.jpg)
HTTP Headers 傻瓜教程[译]
2010-01-25 12:48:00
![](/file/UploadPic/20101/25/http_diagram-83s.png)
SQL中Groupby和Having的使用方法
2008-12-29 13:54:00
从客户端提升SQL Server数据库性能
2009-03-06 14:27:00
oracle 存储过程和函数例子
2009-08-08 22:27:00
golang 使用sort.slice包实现对象list排序
2023-06-21 18:25:46
![](https://img.aspxhome.com/file/2023/2/87612_0s.png)
数字人组件反写[asp组件开发实例3]
2009-06-09 13:16:00
![](https://img.aspxhome.com/file/UploadPic/20093/9/200939182818419s.gif)
正确认识MySQL对服务器端光标的限制
2008-12-03 15:52:00
如何用ASP建立Index Server查询对象并为其参数赋值?
2010-06-11 19:59:00
Go程序性能优化及pprof使用方法详解
2023-08-28 14:04:40
![](https://img.aspxhome.com/file/2023/3/99063_0s.png)
python global关键字的用法详解
2023-12-30 03:32:02
利用Python查看目录中的文件示例详解
2023-02-06 14:13:28
浅谈解除装饰器作用(python3新增)
2022-05-30 03:31:52
部署Django到阿里云服务器教程示例
2022-03-28 23:46:19
![](https://img.aspxhome.com/file/2023/8/64958_0s.png)
Python科学计算之Pandas详解
2023-07-21 19:12:51
![](https://img.aspxhome.com/file/2023/4/81864_0s.png)
教你轻松掌握MaxDB和MySQL之间的协同性
2009-02-23 17:28:00
微信小程序简单的canvas裁剪图片功能详解
2023-08-24 07:49:20
python监控文件或目录变化
2023-09-05 16:08:28
Python画图学习入门教程
2023-11-29 07:43:03