-3

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

1 Answers1

0

Let's break down what you did:

random.choice(list(d.items()) for i  in range(3))

# To

temp_ = []
for i in range(3):
    temp_.append(d.items())
random.choice(temp_)

The code you made will give us a random choice of 3 copies of d.items()

In order for you to get multiple random choices from d.items() (I'm assuming that this is your question) you can do:

choices = []
for i in range(3):
    choices.append(random.choice(list(d.items())))

# Or, to avoid duplicates

choices = []
temp = list(d.items()) # Make temp variable so you avoid mutation of original dictionary.
for i in range(3):
    choices.append(temp.pop(random.randint(0,len(temp)-(i+1))))

If you want to do this via comprehension:

choices = [random.choice(list(d.items())) for i in range(3)] # This is different than your code because it takes a random choice of `d` 3 times instead of taking a choice from three copies.

# Or to avoid duplicates

temp = list(d.items()) # You don't need this, but it's better to keep it here unless you won't need the original dictionary ever again in the program
choices = [temp.pop(random.randint(0,len(temp)-(i+1))) for i in range(3)]
12944qwerty
  • 2,001
  • 1
  • 10
  • 30
  • Thats great he removal of duplicates will be really useful. many thanks. – milesabc123 May 02 '21 at 16:00
  • No problem! But please remember to be more specific in your questions. Just because I managed to understand this time, doesn't mean I also will next time. – 12944qwerty May 02 '21 at 16:18