python - 在Python中重写这个嵌套IF语句的正确方法是什么

标签 python if-statement dictionary

我有一本具有以下结构的字典:

{ "123" : {"red" : ['some text', datetime.datetime(2011, 8, 23, 3, 19, 38), status]},
  "456" : {"red" : ['some other text', datetime.datetime(2013, 8, 23, 3, 19, 38), status],
           "blue" : ['some more text', datetime.datetime(2010, 8, 23, 3, 19, 38), status]},
  "789" : {"blue" : ['random text', datetime.datetime(2012, 8, 23, 3, 19, 38), status],
           "yellow" : ['text', datetime.datetime(2009, 8, 23, 3, 19, 38), status]}}

现在我有了一些更新这本词典的逻辑。它首先检查该字典中是否已存在条目,如果存在则子条目是否存在,并比较时间和更新。如果其中之一不存在,它将创建一个新条目:

if example_id in my_directory:
    if color in my_directory[example_id]:
        if time > my_directory[example_id][color][1]:
            my_directory[example_id][color] = [text, time, status]
    else:
        my_directory[example_id] = {color : [text, time, status]}
else:
    my_directory[example_id] = {color : [text, time, status]}

显然,时间颜色状态作为已存在的变量传递。重写此 IF 语句以不重复第二个和第三个目录更新命令的正确方法是什么?谢谢!

最佳答案

正如其他人所说,使用defaultdict:

my_dictionary = collections.defaultdict(
                lambda: collections.defaultdict(
                lambda: (None, datetime.datetime.min, None)))

# populate my_dictionary

_, old_time, _ = my_dictionary[example_id][color]
if time > old_time:
    # NB: tuples make more sense here than lists
    my_directory[example_id][color] = (text, time, status)

这会临时向您的字典添加一个(None, datetime.datetime.min, None)元组,然后将其替换为实际值。

关于python - 在Python中重写这个嵌套IF语句的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26760287/

相关文章:

python - 在 Python 中反转 C 风格格式字符串 (`%` )

python - 使用列表理解的 if 语句的字典理解

swift - 测试字典中是否存在 nil 值

python - 找到使每个字典在多个字典中唯一的键的最小数量

python - 将 CSV 转换为 XML

python - 如何将文件上传到子文件夹,即使它不存在

python - 使用boto3下载Lambda函数的部署包

javascript - Google App Script 检查编辑的单元格是否包含空格

excel - 嵌套 IF Excel - 替代方案

c# - WPF VS2013 : An error occurred while finding the resource dictionary