0

I want to return Caracas with Venezuela and Toronto with Canada. I want to use Caracas as part of my question in a quiz I am developing, and to use Venezuela as the secret answer to that question. Code:

import random
d = {'Venezuela': 'Caracas', 'Canada': 'Toronto'}
def random_pair(x):
    print(random.choice(list(x.keys() and x.values())))
random_pair(d)

Returns: Toronto or: Caracas I want it to return: Canada Toronto or: Venezuela Caracas I even tried

print(random.choice(list(d.keys()))
print(random.choice(list(d.values()))

but that could return Caracas while returning Canada.

2 Answers2

1

Use d.items() instead of d.keys() and d.values().

DYZ
  • 55,249
  • 10
  • 64
  • 93
0

d.keys() and d.values() are not ordered. They are each in an arbitrary order, which is why they don't match when you try to pick from a list of them.

d.items() gives you the key & value as a pair, together, so you can safely choose a random element.

Alternatively, you can also pick a random key k, and just lookup the associated value: dict[k] which will equal the value.

TemporalWolf
  • 7,727
  • 1
  • 30
  • 50