温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-25 21:32:04 来源:脚本之家 阅读:196 作者:风中摇曳的叶子 栏目:开发技术

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

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

host_key,product_id,product_name,cont_start,cont_end
ah3.zhangyue.com,100002,掌阅,bookId=,&startChapterId
ih3.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字典循环添加一键多值的用法实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI