I am making a programme that will read in a large dictionary. And part of its function will be to choose a number of random items from the dictionary, this is the example of the code:
import random
d = {'VENEZUELA': 'CARACAS', 'CANADA': 'OTTAWA', 'UK': 'LONDON', 'FRANCE': 'PARIS', 'ITALY': 'ROME'}
random_cnty = random.choice(list(d.items())
print(random_cnty)
What I am trying to do is create a dictionary comprehension that chooses a random dictionary entry and repeats the process for a defined range so I end up with a list of unique dictionary key.value pairs (with no duplicates).
I have tried the following but I get syntax errors:
random_countries = random.choice(list(d.items()) for i in range(3))
Can a range and a random function be added to a dictionary comprehension at the same time?
The traceback I get is :
Traceback (most recent call last): File "/Users/home/Dropbox/Python_general_work/finished_projects/python/Scratch.py", line 38, in random_countries = random.choice(list(d.items()) in range(3)) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py", line 347, in choice return seq[self._randbelow(len(seq))] TypeError: object of type 'bool' has no len()
Many thanks