欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python字典循環(huán)添加一鍵多值的用法實例

 更新時間:2019年01月20日 11:39:29   作者:風中搖曳的葉子  
今天小編就為大家分享一篇Python字典循環(huán)添加一鍵多值的用法實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

循環(huán)寫入字典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#此處關鍵產(chǎn)生鍵值對,其中key是id
  read_dict.pop('product_id')#刪除key為‘product_id'的鍵值對
  return read_dict
read_dict=makeDict()

循環(huán)寫入一鍵對多值:

其中格式{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)#此處為關鍵向字典里已經(jīng)有的key(name)值后繼續(xù)添加value(host)
      else:
        host_dict.setdefault(name,[]).append(host)#創(chuàng)建{name,[host]}value為列表的格式的字典。
  return host_dict
host_dict=makehostDict()
print host_dict

以上這篇Python字典循環(huán)添加一鍵多值的用法實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論