我有一个结构如下的字典:
{ "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) 元组到您的字典,然后用实际值替换它。
