0

I need to create a dictionary with Locks as values, but I can't use dict.fromkeys because it creates only one Lock and multiple references:

my_dict = dict.fromkeys(list_of_keys, Lock())

So I do it like:

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

But I wonder if it's possible to use dict.fromkeys in any way,

wjandrea
  • 23,210
  • 7
  • 49
  • 68

1 Answers1

0

It's not possible. dict.fromkeys() puts the same value (same object) for each element.

But at least, you could use a dict comprehension to make it look nicer:

my_dict = {my_key: Lock() for my_key in list_of_keys}
wjandrea
  • 23,210
  • 7
  • 49
  • 68