优草派  >   Python

python字典中如何一键多值的写入?这篇文章非常值得学习

陈立鑫            来源:优草派

很多 python初学者都想知道在python中,字典如何一键多值的写入?那么今天小编就通过这篇文章来给大家分享两个不错的方法,值得大家观看学习!

python字典中如何一键多值的写入?这篇文章非常值得学习

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

(一)循环写入字典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('
')
        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]

以上就是小编给大家带来的在python字典中一键多值写入的方法,希望大家通过阅读小编的文章之后能够有所收获!如果大家觉得小编的文章不错的话,可以多多分享给有需要的人。

【原创声明】凡注明“来源:优草派”的文章,系本站原创,任何单位或个人未经本站书面授权不得转载、链接、转贴或以其他方式复制发表。否则,本站将依法追究其法律责任。
TOP 10
  • 周排行
  • 月排行