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

yipeiwu_com6年前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小技巧分享

获得当前机器的名字: 复制代码 代码如下: def hostname():         sys = os.nam...

Python Xml文件添加字节属性的方法

实例如下所示: from xml.etree.cElementTree import ElementTree,Element import xlrd import re def re...

pycharm修改file type方式

pycharm修改file type方式

原因 添加一个文件 config.ini, 理论上说该文件会以ini文件格式打开,但是不知道咋的手贱用Text格式打开了。 .ini正确打开方式 .Text正确打开方式 手贱操作后的...

基于asyncio 异步协程框架实现收集B站直播弹幕

前言 虽然标题是全站,但目前只做了等级 top 100 直播间的全天弹幕收集。 弹幕收集系统基于之前的B 站直播弹幕姬 Python 版修改而来。具体协议分析可以看上一篇文章。 直...