簡體   English   中英

如何僅更新字典中的值?

[英]How do I update only values in a dictionary?

我正在嘗試在 Python 中為我的公寓大樓制作一個匿名投票程序。 有128個單位。 我想為每個單元分配一個隨機生成的值。

我生成了單位列表,但鍵:值對是相同的。 看起來 Python 的update()方法需要為我要更新的每個值輸入鍵。 這個過程太長了。

我被困住了。

import random

def create_anonymous_votes():
    unit_numbers = {}

#updates the entire dictionary for unit_numbers
    unit_numbers.update({x: x for x in range(1,129)})

#here is what I was thinking would assign and update each key with a random value, but when I print it only prints the original dictionary.

for unit in range(1,129):
    unit_numbers[0] = random.randint(1,1000)
    

print(unit_numbers)
import random #Import random 
random_vote_list = [] #creates an empty list
for i in range(1,128):
    random_vote_list.append(random.randint(1,1000)) 

print(random_vote_list)

我認為這就是您想要的,它將打印一個包含 128 個單元的列表,每個單元都有一個隨機值!

要瀏覽此列表,請使用random_vote_list[0]將給出第一個,依此類推

您可以迭代您的字典並將隨機值設置為:

dict = {'key1': value1, 'key2': value2, 'key3': value3}

for key in dict:
    dict[key] = value

https://realpython.com/iterate-through-dictionary-python/

您的代碼中的一個問題是您正在更改循環中的項目索引0 將循環中的代碼更改為unit_numbers[unit] = random.randint(1, 1000)它應該做你想做的事。 但是,不要忘記您的 function 應該返回一些東西。 並且您需要實際調用您的函數。 您在問題中發布的代碼會產生NameError

所有這一切......而不是制作一個空字典,然后用你必須更新的數字更新它,你可以讓字典理解中的所有內容:

import random

def create_anonymous_votes():
    """Create a random number for each unit."""
    return {x: random.randint(1, 1000) for x in range(1, 129)}

unit_numbers = create_anonymous_votes()
print(unit_numbers)

您可以使用 random.choices 並在一個 go 中重建整個字典:

from random import choices 

unit_numbers = dict(enumerate(choices(range(1,1001),k=128),1))

print(unit_numbers)
{1: 698, 2: 401, 3: 460, 4: 691, 5: 365, 6: 325, 7: 882, 8: 970, 
 9: 828, 10: 122, 11: 205, 12: 173, 13: 253, 14: 68, 15: 899, 16: 528, 
 17: 308, 18: 550, 19: 15, 20: 53, 21: 834, 22: 70, 23: 156, 24: 588, 
 25: 93, 26: 759, 27: 443, 28: 241, 29: 480, 30: 112, 31: 593, 32: 576, 
 33: 915, 34: 433, 35: 960, 36: 742, 37: 262, 38: 242, 39: 929, 40: 496, 
 41: 287, 42: 426, 43: 741, 44: 675, 45: 154, 46: 640, 47: 44, 48: 667, 
 49: 233, 50: 336, 51: 116, 52: 600, 53: 717, 54: 214, 55: 923, 56: 391, 
 57: 157, 58: 420, 59: 913, 60: 911, 61: 727, 62: 24, 63: 807, 64: 212, 
 65: 456, 66: 814, 67: 514, 68: 631, 69: 2, 70: 456, 71: 596, 72: 771, 
 73: 734, 74: 740, 75: 848, 76: 300, 77: 494, 78: 896, 79: 149, 80: 797, 
 81: 271, 82: 589, 83: 679, 84: 990, 85: 253, 86: 281, 87: 648, 88: 738, 
 89: 179, 90: 350, 91: 871, 92: 73, 93: 589, 94: 938, 95: 653, 96: 413, 
 97: 260, 98: 210, 99: 718, 100: 822, 101: 861, 102: 597, 103: 699, 
 104: 352, 105: 315, 106: 469, 107: 707, 108: 276, 109: 857, 110: 622, 
 111: 50, 112: 935, 113: 659, 114: 543, 115: 851, 116: 157, 117: 549, 
 118: 229, 119: 66, 120: 163, 121: 659, 122: 337, 123: 952, 124: 789, 
 125: 182, 126: 566, 127: 770, 128: 636}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM