创建一个字典,每次使用它的值都会更新

我想创建一个每次使用时都会更新其键的字典


我尝试过的:


import itertools


changing_dict = {

    "key1": next(change),

    "key2": next(change),

    "key3": next(change),

    "key4": 10010

}


print(changing_dict)

# Output

# {'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}


print(changing_dict)

# Output

# {'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}


预期产出



print(changing_dict)

# Output

# {'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}


print(changing_dict)

# Output

# {'key1': 115, 'key2': 120, 'key3': 125, 'key4': 10010}


关于我如何做到这一点的任何帮助,或者这是否可能因为在创建 dict 时计算可迭代值。


实际的问题是创建配置文件,每次使用这个 dict 时,我都会用新的端口号来获取它。


达令说
浏览 130回答 2
2回答

德玛西亚99

尝试使用这个函数,你可以有一个函数,所以每次运行时,change变量都会不同:change = iter(range(100, 200, 5)) # just an exampledef next_dict():    changing_dict = {        "key1": next(change),        "key2": next(change),        "key3": next(change),        "key4": 10010    }    return changing_dictprint(next_dict())print(next_dict())输出:{'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}{'key1': 115, 'key2': 120, 'key3': 125, 'key4': 10010}

慕村9548890

您可以定义一个类而不是这样的字典:change = iter(range(5))class c:    def get_key1():        return next(change)c.get_key1() # Output: 0c.get_key1() # Output: 1像某些评论一样,我建议您提供更多上下文,因为可能会有更多“Pythonic”来解决您的用例。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python