我有一个 python 字典,它不时添加信息。
状况:
例子:
result = {}
def add_key(key, val):
test = result.get(key) # Test to see if key already exists
if test is None:
if len(result.keys()) < 3:
result[key] = val # This key and pair need to be deleted from the dictionary after
# 24 hours
else:
# Need code to remove the earliest added key.
add_key('10', 'object 2')
## Need another code logic to delete the key-value pair after 24 hours …Run Code Online (Sandbox Code Playgroud) ldict1 = [{"id":1, "name":"apple", "colour": "", "type": ""},
{"id":2, "name":"orange", "colour": "", "type":""}]
ldict2 = [{"id":1, "colour":"red", "type":"fruit"},
{"id":2, "colour":"orange", "type":"fruit"}]
Run Code Online (Sandbox Code Playgroud)
上面是我想要合并的两种类型的字典列表的示例。两者的 id 相同。两者的长度都很长。我只能想到嵌套 for 循环,但这可能需要时间。合并相同内容的最快方法是什么?
预期的
ldict = [{"id":1, "name":"apple", "colour": "red", "type": "fruit"},
{"id":2, "name":"orange", "colour": "orange", "type":"fruit"}]
Run Code Online (Sandbox Code Playgroud)
请注意,两个列表始终具有相同的 id 顺序。ldict1另外,我想添加from缺少的细节ldict2。这些键始终为空,ldict1需要用 来填充ldict2。