是否创建并向字典添加递增键?

2024-05-18 14:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,一直无法通过各种google搜索找到答案。本质上,我试图通过一个函数向字典添加一个新键。我需要这个函数来创建一个唯一的键,该键在每次通过循环时递增。这些键的值将作为已填充的对象输入

我希望做的事情的示例:

dict = {}
looper = 0
While looper < 100:
    dict[newkey1] = value
    looper += 1

最终,我需要的结果是一本字典,如下所示:

dict = {newkey1 : value1, newkey2 : value2, newkey3 : value3, ...}

这些值将由一个数学函数创建,并从我的脚本的前面部分传递到值槽中

我不确定我的问题是否有答案。我可能从一开始就错误地构建了我的程序

编辑** 大家好,非常感谢你们的回答。在阅读了下面的答案并实施了其中的一些之后,我想我对我要寻找的东西有了更好的理解

简而言之,我正在做的是:我有一个名为window的类。窗口有4个不同的属性。我希望用户将这些属性输入到一个新对象中。创建对象后,我希望将该对象作为键存储在字典中。该值将设置为0以开始。然后,我将根据一个不相关的数学方程更新该值。我需要做的是创建一个新的递增对象:

win1 = Window(var1 = input("please input var1:", etc, etc, etc).

win1是我每次需要递增并保存到字典中的内容。 这将只是在终端上运行,因为我还没有自学GUI

基本上,它将按如下方式运行:

#user enters win1 and variables.
more_win = input("Do you have another window to enter?")

while more_win == "yes":
   # this is where I dont know what to do
   # program needs to generate a new object that is incremented
   # and then stored within a dictionary having the value of that newly 
   # incremented key be 0 EX(win1: 0, win2 : 0, etc, etc)
win2 = Window(var1 = input(...), etc, etc, etc)

我希望这是有意义的!我讨厌问一个愚蠢的问题,我只是不知道在这里搜索什么


Tags: to对象函数答案input字典valueetc
2条回答

如果希望每次生成一个唯一密钥,可以通过导入python uuid包执行以下操作:

import uuid

dict = {}
looper = 0
while looper < 100:
    key = uuid.uuid4()
    dict[key] = value
    looper += 1

# output: 
# {UUID('b7feb1c6-f070-4424-968a-f73438bbf7a8'): Value 0,
# UUID('524db4db-aa2a-41af-b794-827f896b8101'): Value0 1,
# UUID('b1a67189-531f-4590-bd03-8d66f44b46b3'): Value0 2,..}

否则,如果要创建一个每次递增的唯一密钥,可以通过将looper设置为密钥执行以下操作:

dict = {}
looper = 0
while looper < 100:
    key = looper
    dict[key] = value
    looper += 1

作为第一个通行证,这是您要寻找的:

def add_value(dx: dict, new_value) -> dict:
  max_key = int(sorted(dx.keys())[-1])
  dx[max_key + 1] = new_value
  return dx

不过,这里有一些警告:

  • 它假设字典中的所有键都可以解析为int。否则,它将失败
  • 它会在每次通话中进行分类,这可能会耗费大量时间

如果可以保证字典中没有添加其他键,则可能不需要函数:

original_dictionary: dict = ...
sorted_dictionary = {k: original_dictionary[k] for k in sorted(original_dictionary.keys())}
...
// Whenever you add a key
new_idx = sorted_dictionary.keys()[-1]
sorted_dictionary[new_idx] = new_value

这是因为在Python3.7+中,字典保留其键排序顺序

相关问题 更多 >

    热门问题