简体   繁体   中英

How can I use a loop to get values for dictionary without overwriting the previous value?

I have to save a dictionary on a seprate json file. The values for the dictionary are being scraped forom a website. I want the values to add up but with every new one the old one is replaced.

gar = -1
Pirmasfilmasvaroni = varoni[gar]
while (gar < 7): 
  gar = gar + 1
  
  #atdaliju varonus atkariba no filnmas


  #cik varoni
  garums = len(Pirmasfilmasvaroni)
  z = (garums-1)
  u = (z-1)
 
  count = -1 
  while (count < z):   
    count = count + 1
    pirmais = Pirmasfilmasvaroni[count]
    Psaturs = requests.get(pirmais)


    if Psaturs.status_code == 200:
     Pdati = Psaturs.text
     Pinfo = json.loads(Pdati)
     var = Pinfo['result']['properties']['name']


     dic = {gar:[var]}
       
     with open("Filmas_un_varoni_kas_tajas_piedalas.json", "w") as js:
       json.dump(dic, js, indent=4)
varoni={}
gar = -1 
Pirmasfilmasvaroni = varoni[gar]

# create an empty dictionary
dic = {}

while (gar < 7): 
  gar = gar + 1
  
  #atdaliju varonus atkariba no filnmas


  #cik varoni
  garums = len(Pirmasfilmasvaroni)
  z = (garums-1)
  u = (z-1)
 
  count = -1 
  while (count < z):   
    count = count + 1
    pirmais = Pirmasfilmasvaroni[count]
    Psaturs = requests.get(pirmais)


    if Psaturs.status_code == 200:
     Pdati = Psaturs.text
     Pinfo = json.loads(Pdati)
     var = Pinfo['result']['properties']['name']

     # add the new key-value pair to the dictionary
     dic[gar] = var

# write the dictionary to the json file
with open("Filmas_un_varoni_kas_tajas_piedalas.json", "w") as js:
   json.dump(dic, js, indent=4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM