您的位置:首页 > 技术中心 > 其他 >

python字典中如何一键多值的写入?

时间:2020-06-23 13:50

python字典中如何一键多值的写入?

python字典中一键多值写入的方法:

1、循环写入字典key、value、删除指定的键值对:

原文本‘jp_url.txt’每行元素以逗号分隔:

  1. host_key,product_id,product_name,cont_start,cont_end
  2. ah2.zhangyue.com,100002,掌阅,bookId=,&startChapterId
  3. ih2.ireader.com,100002,掌阅,bid=,&
  4. www.ireader.com,100002,掌阅,&bid=,&cid
  5. m.zhangyue.com,100002,掌阅,readbook/,/
  6. c13.shuqireader.com,100003,书旗,bookId=,&chapterId
  7. t.shuqi.com,100003,书旗,bid/,/cid
  8. 想要得到:
  9. {‘100002’:‘product_name’.......}

代码如下:

  1. def makeDict():
  2. fileRead=open('jp_url.txt','rb')
  3. lines=fileRead.readlines()
  4. read_dict={}#定义字典
  5. for line in lines:
  6. line_list=line.split(',')#每行按逗号分隔成列表
  7. id=line_list[1]#取到id
  8. name=line_list[2]#取到name
  9. read_dict[id]=name#此处关键产生键值对,其中key是id
  10. read_dict.pop('product_id')#删除key为‘product_id’的键值对
  11. return read_dict
  12. read_dict=makeDict()

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. def makehostDict():
  2. host_dict={}
  3. f_allhost=open('xml_host.txt','rb')
  4. lines=f_allhost.readlines()
  5. for line in lines:
  6. line_list=line.split('|')
  7. name=line_list[0]
  8. host=line_list[1].strip('\n')
  9. if host is not '':
  10. if host_dict.has_key(name):
  11. host_dict.get(name).append(host)#此处为关键向字典里已经有的key(name)值后继续添加value(host)
  12. else:
  13. host_dict.setdefault(name,[]).append(host)#创建{name,[host]}value为列表的格式的字典。
  14. return host_dict
  15. host_dict=makehostDict()
  16. print host_dict

推荐教程:《python视频教程》

以上就是python字典中如何一键多值的写入?的详细内容,更多请关注gxlsystem.com其它相关文章!

热门排行

今日推荐

热门手游