字典理解添加一个范围

Dictionary Comprehensions add in a range

我正在制作一个可以在大词典中阅读的程序。它的一部分功能是从字典中选择一些随机项目,这是代码示例:

import random
d = {'VENEZUELA': 'CARACAS', 'CANADA': 'OTTAWA', 'UK': 'LONDON', 'FRANCE': 'PARIS', 'ITALY': 'ROME'}
random_cnty = random.choice(list(d.items())
print(random_cnty)

我想做的是创建一个字典理解,它选择一个随机的字典条目并在定义的范围内重复该过程,所以我最终得到一个独特的字典 key.value 对列表(没有重复项).

我尝试了以下方法,但出现语法错误:

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

范围和随机函数可以同时添加到字典推导中吗?

我得到的回溯是:

回溯(最后一次调用): 文件“/Users/home/Dropbox/Python_general_work/finished_projects/python/Scratch.py”,第 38 行,位于 random_countries = random.choice(范围(3)中的列表(d.items())) 选择文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py”,第 347 行 return序列[self._randbelow(len(序列))] 类型错误:'bool' 类型的对象没有 len()

非常感谢

让我们分解一下你做了什么:

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

# To

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

您制作的代码会给我们随机选择3份d.items()

为了让您从 d.items() 中获得多个随机选择(我假设这是您的问题)您可以这样做:

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))))

如果你想通过理解来做到这一点:

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)]