SoFunction
Updated on 2024-11-13

Python Dictionary Loop Adding Multiple Values to a Key Usage Example

Cyclically writes the dictionary key, value, and deletes the specified key-value pair:

The original text 'jp_url.txt' has each line element separated by a comma:

host_key,product_id,product_name,cont_start,cont_end
,100002,read in the palm of one's hand,bookId=,&startChapterId
,100002,read in the palm of one's hand,bid=,&
,100002,read in the palm of one's hand,&bid=,&cid
,100002,read in the palm of one's hand,readbook/,/
,100003,banner,bookId=,&chapterId
,100003,banner,bid/,/cid

Want to get:

{‘100002':‘product_name'.......}

The code is as follows:

def makeDict():
  fileRead=open('jp_url.txt','rb')
  lines=()
  read_dict={}#define dictionary
  for line in lines:
    line_list=(',')# Each line is a comma-separated list
    id=line_list[1]# Fetch the id
    name=line_list[2]# Fetch the name
    read_dict[id]=name# Here the key generates a key-value pair, where key is id
  read_dict.pop('product_id')# Delete key-value pairs with key 'product_id'
  return read_dict
read_dict=makeDict()

Cyclic writing of one key to multiple values:

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

The text txt format is as follows:

guaguashipinliaotianshi|.,
guaguashipinliaotianshi|,
guaguashipinliaotianshi|.,
jiuxiumeinvzhibo|.,
nbazhibo|.,
youbo|,

The first column of the name has a duplicate want a name corresponds 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=('|')
    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 the key adds value(host) to the key(name) already in the dictionary.
      else:
        host_dict.setdefault(name,[]).append(host)# Create a dictionary in the format {name, [host]}value as a list.
  return host_dict
host_dict=makehostDict()
print host_dict

The above example of the usage of this Python dictionary loop to add multiple values to a key is all that I have shared with you, I hope it will give you a reference, and I hope you will support me more.