简体   繁体   English

Dictionary 中的哪些键值未更新?

[英]Which key values in Dictionary were not updated?

I have a dictionary whose keys are integers and values are lists, for each key list is updated in every iteration.我有一个字典,它的键是整数,值是列表,因为每个键列表在每次迭代中都会更新。 Also new keys are added.还添加了新密钥。 But there may be situations where some key values are not updated.但是可能会有一些关键值没有更新的情况。

whats the most efficient way to know which keys were not updated?知道哪些键未更新的最有效方法是什么?

I can iterate all lists in dictionary and check from length if that list was updated or not but is there a better way?我可以迭代字典中的所有列表并从长度检查该列表是否已更新但有更好的方法吗?

Note: Integer Keys are not consecutive numbers.注意: Integer 键不是连续的数字。 Therefore using simple lists or arrays does not seem like an option因此使用简单列表或 arrays 似乎不是一个选项

As an alternative to the solution @Scott Skiles made in a comment, I would add a value to the dictionary, next to the list, that designates the most recent iteration when the key was modified:作为@Scott Skiles 在评论中提出的解决方案的替代方案,我将在列表旁边的字典中添加一个值,该值指定修改键时的最新迭代:

my_dict = {}
iteration_num = 0
while True:
    updates_to_make = some_function_producing_2tuples()
    # iterate through new additions, and add them to the list
    for key, value in updates_to_make:
        # the 'value' in my_dict is a 2-tuple (last_updated, list)
        # we replace last_updated every time we change the key somehow
        if key in my_dict:
            my_dict[key][1].append(value)
            my_dict[key][0] = iteration_num
        else:
            my_dict[key] = (iteration_num, [value])
    ...
    iteration_num += 1

You can then figure out which keys are or are not updated by applying a filter:然后,您可以通过应用过滤器来确定哪些键已更新或未更新:

updated_keys = [k for k, v in my_dict.items() if v[0] == iteration_num]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM