我有一本具有以下结构的字典:
{ "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/