How to write multiple values with one key in python dictionary?

coldplay.xixi
Release: 2020-06-23 13:50:06
Original
5842 people have browsed it

How to write multiple values ​​with one key in python dictionary?

#How to write multiple values with one key in a python dictionary?

One-key multi-value writing method in python dictionary:

1. Loop to write dictionary key, value, and delete the specified key-value pair:

The original text 'jp_url.txt' elements in each line are separated by commas:

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’.......}
Copy after login

The code is as follows:

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()
Copy after login

2. Loop to write one-click to many values:

The format{key:[value1,value2,...]}

The text txt format is as follows:

  • guaguashipinliaotianshi| .guagua.cn,

  • guaguashipinliaotianshi|iguagua.net,

  • guaguashipinliaotianshi|.17guagua.com,

  • jiuxiumeinvzhibo|.69xiu.com,

  • nbazhibo|.estream.cn,

  • youbo|yb.sxsapp.com,


The names in the first column are repeated. If you want one name to correspond to multiple results, the code is as follows:

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
Copy after login

Recommended tutorial: "python Video tutorial

The above is the detailed content of How to write multiple values with one key in python dictionary?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!