2

I'm trying to make a game where the user is asked to guess a country based on it's capital which is selected at random from a list of dictionaries (similar to the link at bottom).

Guessing 10 countries in total, if they guess correctly they get 1 point, with 10 points in total.

I've imported a variable 'countries' that contains a list of dictionaries like the following:

[{'capital': 'Andorra la Vella',
  'code': 'AD',
  'continent': 'Europe',
  'name': 'Andorra',
  'timezones': ['Europe/Andorra']},
 {'capital': 'Kabul',
  'code': 'AF',
  'continent': 'Asia',
  'name': 'Afghanistan',
  'timezones': ['Asia/Kabul']},

So how do I print a random choice from a specific key name? In this case, any 'capital' from any of the dictionaries.

Python-Dictionary states and capital game

Sach
  • 904
  • 8
  • 20
  • something like `import random print(capitals[random.randint(0, len(capitals) - 1)]['capital'])` assuming `capitals`is the list you have given. edit: much simplier with `random.choice()` actually. Thanks @Jeppe ! – rene-d Feb 08 '19 at 12:28
  • 2
    Simply use [`random.choice()`](https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list), which gives you a random dictionary. You can then fetch the capital from the returned dictionary and access the country when you check the user-input. – Jeppe Feb 08 '19 at 12:28
  • @rene-d The [implementation](https://github.com/python/cpython/blob/master/Lib/random.py#L278) of `random.choice()` actually looks pretty much like your code. – Jeppe Feb 08 '19 at 12:53
  • @LaurenToulson Great - welcome to Stack Overflow. – Jeppe Feb 09 '19 at 09:27

4 Answers4

0

You can use below two options.

  1. random.choice to select a random element from a the list.

Sample code.

from random import choice
country_dict = [{'capital': 'Andorra la Vella',     'code': 'AD',  continent': 'Europe',      'name': 'Andorra',      'timezones': 'Europe/Andorra']},
                {'capital': 'Kabul',      'code': 'AF',      'continent': 'Asia',      ame': 'Afghanistan',      'timezones': ['Asia/Kabul']}
               ]
country = choice(country_dict)
capital = input("Please enter the captial for country "+country['name'])
if capital == country['capital']:
    print("Correct answer")
  1. random.ranint to select random integer between 0 and length of list.

Sample code:

from random import randint
country_dict = [{'capital': 'Andorra la Vella',      'code': 'AD',      'continent': 'Europe',      'name': 'Andorra',      'timezones': ['Europe/Andorra']},
                {'capital': 'Kabul',      'code': 'AF',      'continent': 'Asia',      'name': 'Afghanistan',      'timezones': ['Asia/Kabul']}
               ]
ind = randint(0,len(country_dict)-1)
capital = input("Please enter the captial for country "+country_dict[ind]['name'])
if capital == country_dict[ind]['capital']:
    print("Correct answer")
Sach
  • 904
  • 8
  • 20
0

You can fetch a random sample with randomCountry = random.choice(countries)

However, if you do this multiple times, you may get the same country multiple times. To combat this, you could sample 10 distinct elements with randomCountries = random.sample(countries, 10) and then iterate with those.

Note that random.sample throws an error if you attempt to sample more elements than there exists in the collection.

Your game could thus look like this:

import random

countries = [
    {'capital': 'Andorra la Vella', 'code': 'AD', 'continent': 'Europe', 'name': 'Andorra', 'timezones': ['Europe/Andorra']}, 
    {'capital': 'Kabul', 'code': 'AF', 'continent': 'Asia', 'name': 'Afghanistan', 'timezones': ['Asia/Kabul']},
    ...
]

rounds = 10
random_countries = random.sample(countries, rounds) # returns 10 random elements (no duplicates)

score = 0
for country in random_countries:
    print("Score: %d / %d | Which country has the capital: %s?" % (score, rounds, country['capital']))
    country_response = input()
    if country_response == country['name']:
        score += 1
        print("Correct")
    else:
        print("Incorrect")
Jeppe
  • 1,830
  • 3
  • 24
  • 33
0

random.choice is very good for this use case :)

import random


country_dlist = [{'capital': 'Andorra la Vella',
  'code': 'AD',
  'continent': 'Europe',
  'name': 'Andorra',
  'timezones': ['Europe/Andorra']},
 {'capital': 'Kabul',
  'code': 'AF',
  'continent': 'Asia',
  'name': 'Afghanistan',
  'timezones': ['Asia/Kabul']}
 ]

def run():
    tot_points = 0
    num_of_ques = len(country_dlist)
    for i in range(num_of_ques):
        choice = random.choice(country_dlist)
        que = country_dlist.remove(choice)
        capital = raw_input("Please enter the captial for country {}: ".format(choice['name']))
        if capital.lower() == choice['capital'].lower(): # case insensitive match :)
            tot_points += 1
    return tot_points

points = run()
print("You scored {} points".format(points))
han solo
  • 6,390
  • 1
  • 15
  • 19
-2

like this?

import random
place_list = [{'capital': 'Andorra la Vella', 'code': 'AD', 'continent': 'Europe', 'name': 'Andorra', 'timezones': ['Europe/Andorra']}, {'capital': 'Kabul', 'code': 'AF', 'continent': 'Asia', 'name': 'Afghanistan', 'timezones': ['Asia/Kabul']}]
quiz_length = 10
points = 0
for q in random.sample(place_list, quiz_length):
    guess = input(f'this place has {q['capital']} in it')
    if guess == q['name']:
        points += 1
print(f'you got {points}/{quiz_length}')

edit: the rest of the code...

Rhys
  • 1
  • 1
  • 8