Python dictionary loop add one-key multi-value usage

Write the dictionary key, value, and delete the specified key-value pair in a loop :

Each line of the original text 'jp_url.txt' is 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
Want to get:
{‘100002’:‘product_name’.......}

code show as below:

def makeDict():
    fileRead=open('jp_url.txt','rb')
    lines=fileRead.readlines()
    read_dict={}#Define dictionary
    for line in lines:
        line_list=line.split(',')#Each line is separated into a list by commas
        id=line_list[1]#Get the id
        name=line_list[2]#取到name
        read_dict[id]=name#The key here produces a key-value pair, where key is id
    read_dict.pop('product_id')#Delete the key-value pair whose key is 'product_id'
    return read_dict
read_dict=makeDict()

Write a key-to-many value in a loop :

Where 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 name of the first column is repeated. I 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)#here is the key to the existing key(name) value in the dictionary and continue to add value(host)
            else:
                host_dict.setdefault(name,[]).append(host)#Create a dictionary in the format of {name, [host]}value as a list.
    return host_dict
host_dict=makehostDict()
print host_dict





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325566845&siteId=291194637