1

I have an issue with my code. I made a list where i have cities and their postcodes listed. The script is supposed to be a web automation that randomly chooses a city and its postcode. It has to enter the city in one input field and postcode in another one. My code looks like this and the problem is that it chooses city randomly, but it doesn't select postcode in other field, instead it chooses another random city.

from webbot import Browser
import random

d = {'Presov':'08001', 'Zilina':'01001', 'Nove Zamky':'94062'}

web.type((random.choice(list(d))) , into='City')
web.type('Netherlands' , into='State, Province, or Region')
web.type((random.choice(list(d))) , into='Postal Code')
2
  • Yeah, well, you're picking a random value twice. You'll want to pick a random key once, then use that randomly picked key to get the value from d. Commented Apr 7, 2021 at 9:33
  • list(d) only gives you key. Use list(d.items()). Commented Apr 7, 2021 at 9:34

1 Answer 1

7

Choose the random key and then get the postcode.

import random

d = {'Presov':'08001', 'Zilina':'01001', 'Nove Zamky':'94062'}

random_city = random.choice(list(d))
postcode = d[random_city]
print(random_city, postcode)

# alternatively

random_city, postcode = random.choice(list(d.items()))
print(random_city, postcode)

# and then
web.type(random_city, into='City')
web.type('Netherlands' , into='State, Province, or Region')
web.type(postcode, into='Postal Code')
Sign up to request clarification or add additional context in comments.

2 Comments

that makes sense but how would i put it into the web.type code?
here you have, if that solves your issue please mark it as solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.