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

yipeiwu_com5年前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警察与小偷的实现之一客户端与服务端通信,分享给大家供大家参考。具体方法分析如下: 该实例来源于ISCC 2012 破解关第四题 目的是通过逆向police,实...

django一对多模型以及如何在前端实现详解

models.py class xm(models.Model): xmID=models.AutoField(primary_key=True) xmTitle=model...

python向已存在的excel中新增表,不覆盖原数据的实例

每月需更新某个excel表格,进行两项操作,且不覆盖原有的sheet: 1. 在原来的excel表中新增sheet 2. 往原有的excel表中的某张sheet新增内容 基于python...

浅谈pyqt5中信号与槽的认识

一、介绍 信号(Signal)和槽(Slot)是Qt中的核心机制,也是PyQt变成中对象之间进行通信的机制 在pyqt5中,每一个QObject对象和pyqt中所有继承自QWidge...

使用Pyinstaller转换.py文件为.exe可执行程序过程详解

使用Pyinstaller转换.py文件为.exe可执行程序过程详解

 前言 pyinstaller能够在Windows、Linux等操作系统下将Python脚本打包成可直接运行程序。使Python脚本可以在没有安装Python的环境中直接运行,...