-2

I want to get a value "element":"value" from a dictionary in python.

import random

country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
} 

random.choice(country)

It returns me the following :

File "C:\Users\${username}\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 262, in choice
    return seq[i]
KeyError: 10

My aim, is to select a random value and be left with 1 Country - City left in the dictionary. This does not answer my question : How to get a random value from dictionary in python

  • Use the solution in the duplicate to get random key. It's value is `country[key]`. So `{key: country[key]}` is what you want. – Austin Nov 21 '19 at 18:11

4 Answers4

0

You can use the items method to get the pairs, then transform it to a list that supports indexing: random.choice(list(country.items()))

Horace
  • 1,024
  • 7
  • 12
0

i think you can implement in following way

import random

country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
keys = list(country.keys())
random_key = keys[random.randint(0, len(keys)-1)]
print(country[random_key])
Yukun Li
  • 244
  • 1
  • 6
0

You can make a random.choice from the keys() of the dict for instance.

You could print the values or make a new dict with just that entry:

import random

country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}

k = random.choice(list(country.keys()))
print(k, country[k])
print({k:country[k]})
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

First of all, there's no order in a dictionary. The only list can be used for random.sample.

So change your code to random.choice(list(country.items()))

Bill Chen
  • 1,699
  • 14
  • 24