小编nif*_*eco的帖子

暂时将键和值保留在字典中

我有一个 python 字典,它不时添加信息。

状况:

  1. 字典中的键始终不应超过 3 个。如果需要添加另一个键值对,则应删除此时字典中最早添加的键,并添加新的键值对。
  2. 添加键值后,1 天后应将其删除。

例子:

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)

python datetime dictionary

3
推荐指数
1
解决办法
871
查看次数

Python将2个字典列表合并为一个字典列表的最快方法

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

python dictionary list python-3.x

0
推荐指数
1
解决办法
90
查看次数

标签 统计

dictionary ×2

python ×2

datetime ×1

list ×1

python-3.x ×1