我有一本具有以下结构的字典:
{ "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]}
显然,time
,color
,和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)
在您的字典中临时添加一个元组,然后将其替换为实际值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句