How to replace request objects from a dict of items using python?

Question:

I have a dict and request body as below.

dict_items = {"country":["india","uk","usa","srilanka"],"city":["delhi","london","new york","colombo"]}

payload = {
    "country": country,
    "city": city
}

How can I replace each country and city in the payload and generate a new request for each value in the dict. I need to get four payloads with each country and city from the dictionary. Please help me with this.

I have tried the following but not helpful.

for key,val in dict_items.items():
    i += 1
    if key == "country":
       for i in range(val):
           req_json['name'] = val[i]
           break
      if i == len(val):
         break

but the above is not giving the expected request objects. I need each request object to get the values from the dictionaries for each country and city.

Asked By: Sivajyothi

||

Answers:

I would start with simplify the problem and getting all countries and cities in separate variables:

countries = dict_items["country"]
cities = dict_items["city"]

Now there are multiple ways, the simplest:

payloads = [{"country": country, "city": city} for country, city in zip(countries, cities)]

Now you can iterate over them and send proper requests or whatever you need them for:

for payload in payloads:
    requests.get(some_url, json=payload)
Answered By: kosciej16
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.