Python Forum
Randomising a value in a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Randomising a value in a dictionary
#1
Hi, so i'm creating a basic quiz which incorporates lists, functions, dictionaries and interactive loops.

The quiz is on Capital Cities. The user is shown a Country and then a Capital City which is chosen at random. The user is asked if it's the right or wrong Capital City. If they are right, they get a message 'Correct, the capital city of .... is ....', if they are wrong they get a message 'Incorrect, the capital city of .... is ....

In terms of where I am at, the program output gives the right capital city everytime and it does not randomise value in otherwords the capital city.

What am I struggling with?
1/ I'm struggling to randomise the dictionary value so that the program randomly chooses whether to give the right or wrong capital city
2/ Once I get part 1 working. How do I then write the 'if' part of the program. So basically: If the user is correct, say correct the capital city of .... is ..... and if they guess incorrect say incorrect, the capital city of .... is ....

In terms of what I have achieved so far, this is what I have got:

from random import *
def show_capital_city():

    random_capital = choice(list(capital_cities))
    print('Define: ', (random_capital))
    print(capital_cities[random_capital])
    input('Is this the right capital city? Enter Y or N')


capital_cities = {'Australia': 'Canberra', 'Brazil': 'Brasilia', 'Cuba': 'Havana',
                  'France': 'Paris', 'Germany': 'Berlin', 'United States': 'Washington D.C'}

# s to start or q to quit if use enters something else ask again
exit = False
while not exit:
    user_input = input('Enter s to start and q to quit: ')
    if user_input == 'q':
        exit = True
    elif user_input == 's':
        show_capital_city()
    else:
        print('You need to enter either q or s.')
Any help, guidance, tips would be really appreciated!
Reply
#2
Maybe this will help get you started.
#! /usr/bin/env python3
import random as rnd
capital_cities = {
    'Australia': 'Canberra',
    'Brazil': 'Brasilia',
    'Cuba': 'Havana',
    'France': 'Paris',
    'Germany': 'Berlin',
    'United States': 'Washington DC'
}
for i in range(5):
    print(f'Country -> {rnd.choice(list(capital_cities.keys()))} Capital -> {rnd.choice(list(capital_cities.values()))}')
Output:
Country -> Cuba Capital -> Havana Country -> Cuba Capital -> Paris Country -> United States Capital -> Berlin Country -> Brazil Capital -> Berlin Country -> Australia Capital -> Berlin
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
Here is one way to go about it:

from random import shuffle

capital_cities = {'Australia': 'Canberra', 'Brazil': 'Brasilia', 'Cuba': 'Havana',
                  'France': 'Paris', 'Germany': 'Berlin', 'United States': 'Washington D.C'}
random_city_list = [value for key, value in capital_cities.items ()]
shuffle (random_city_list)
marker = 0
for country in capital_cities :
	print (f'Is the capital of {country} {random_city_list [marker]}?')
	guess = input ('Yes or No : ')
	if capital_cities [country] == random_city_list [marker] :
		answer = True
	else : answer = False
	if guess in ('Y', 'y', 'Yes', 'yes') and answer == True or guess in ('N', 'n', 'No', 'no') and answer == False :
		print ('You are correct. ', end = '')
	if guess in ('Y', 'y', 'Yes', 'yes') and answer == False or guess in ('N', 'n', 'No', 'no') and answer == True :
		print ('You are incorrect. ', end = '')
	print (f'The capital of {country} is {capital_cities [country]}.')
	marker += 1
Reply
#4
Here is another way to randomize. In this example the city is chosen at random and may appear more than once. This is slightly different than the shuffle method used by BashBedlam.
import random

capital_cities = {
    'Australia': 'Canberra',
    'Brazil': 'Brasilia',
    'Cuba': 'Havana',
    'France': 'Paris',
    'Germany': 'Berlin',
    'United States': 'Washington D.C'}

for country, capital in capital_cities.items():
    city = random.choice(list(capital_cities.values()))
    answer = input(f'{city} is the capital of {country} [T/F]: ')[0]
    if (answer in ('tT')) == (city == capital):
        if city == capital:
            print('Correct!')
        else:
            print(f'Correct! {capital} is the capital of {country}')
    else:
        print(f'Incorrect.  {capital} is the capital of {country}')
I think all the solutions will be similar. You need to extract countries, capitals or both from the dictionary and put them in lists. You use one of the random function (choice, choices, shuffle) to mix things up. Then you use the randomized values to make your questions.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020