简体   繁体   中英

Python For Loop iterating X times values in list issue

listA = [(UK,1),(USA,2),(UAE,3)]
def fetchdata():
  base_url = 'someurl.com
  params = {countryname : country}
  resp = requests.requests('GET', base_url+params).json()

def upload():
 some sql insert code
for x in lista:
   country = listA[0]
   ID = listA[1]
   fetchdata()
   upload()

Above code works fine. The issue is, because there's three tuples, the SQL will upload data 3 times. If I have five tuples, it will upload data five times. I tried nested list, no luck.

My intention is such that UK will be inserted in JSON parameter, it will fetch data, assign ID/index, upload to SQL the two values. Then it will loop for next country.

What I should get is....

Country ID value
UK 1 50
US 2 100
UAE 3 75

What I am getting is....

Country ID value
UK 1 50
UK 1 50
UK 1 50
US 2 100
US 2 100
US 2 100
UAE 3 75
UAE 3 75
UAE 3 75

Solved it. There was dictionary that needed to be reset before running loop again.

So...

values :{}

and during a for loop

for locations in locations:
  run some code
  values: {}
> for x in lista:

Did you mean listA here?

It might be iterating 5 times for each character in 'lista'

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