You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否使用dict.fromkeys创建值为独立Lock对象的字典?

Can dict.fromkeys() be used to create a dictionary with unique Lock instances per key?

Great question! Let's break this down clearly:

Why dict.fromkeys() doesn't work here

The core issue with dict.fromkeys(list_of_keys, Lock()) is that the second argument to fromkeys() is evaluated only once, at the time you call the function. That means you're creating a single Lock instance, and every key in the dictionary will reference that same instance—exactly the problem you're trying to avoid. fromkeys() is designed specifically for scenarios where you want all keys to map to the same value, so it's not a good fit for unique per-key objects like locks.

Your current solution is solid (and there's a cleaner variant)

Your current approach using a generator expression:

my_dict = dict((my_key, Lock()) for my_key in list_of_keys)

works perfectly because it creates a new Lock instance for every key as it iterates. For a more modern, readable take, you can use a dictionary comprehension (available in Python 2.7 and above):

my_dict = {key: Lock() for key in list_of_keys}

This does the exact same thing but is more concise and intuitive.

Is there any way to force dict.fromkeys() to work?

Short answer: Not really in a clean, idiomatic way. You could hack together something like first creating an empty dictionary with fromkeys() and then overwriting each value with a new Lock, but that's redundant and less efficient than just using a comprehension:

# Not recommended—just use a comprehension instead!
my_dict = dict.fromkeys(list_of_keys)
for key in my_dict:
    my_dict[key] = Lock()

This defeats the purpose of using fromkeys() in the first place, since you're just using it to initialize the keys and then immediately replacing all values.

Final takeaway

Stick with dictionary comprehensions or your existing generator expression—they're the intended, readable ways to create a dictionary where each key maps to a unique instance of an object like Lock. dict.fromkeys() is great for shared values, but not for per-key unique objects.

内容的提问来源于stack exchange,提问作者Camilo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:48:15