python字典中如何一键多值的写入?-Python教程

资源魔 33 0

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('\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视频教程》

以上就是python字典中若何一键多值的写入?的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题 一键多值

抱歉,评论功能暂时关闭!