Reputation: 2485
I know I can make a dictionary with particular keys:
my_dict = dict.fromkeys(my_keys)
and I know I can inherit the dictionary class:
class My_Dict_Class(dict):
...
but how can I combine the two? I want to make a dictionary class and I already know all the keys it will ever have. I know I could set some keys inside my class, but wouldn't it be nicer and quicker if I could do:
class My_Dict_Class(dict.fromkeys(my_keys)):
...
The reason I want to do this is that I've heard fromkeys
is much quicker than looping and setting the keys in this question.
MWE:
my_keys = [1,2,3]
my_dict = dict.fromkeys(my_keys)
class My_Dict_Class(dict):
def my_functions(self):
return
class My_Dict_Class(dict.fromkeys(my_keys)):
def my_functions(self):
return
Traceback (most recent call last):
File "dummy.py", line 8, in <module>
class My_Dict_Class(dict.fromkeys(my_keys)):
TypeError: Error when calling the metaclass bases
dict expected at most 1 arguments, got 3
Upvotes: 1
Views: 899
Reputation: 155353
Python classes inherit from other classes, not class instances. If your goal is to initialize the contents of the dictionary for each instance quickly though, copying an existing dictionary is faster than anything else you could do. For example, you could define:
class MyDict(dict):
_DEFAULT_CONTENTS = dict.fromkeys((1, 2, 3))
def __init__(self):
super(MyDict, self).__init__(self._DEFAULT_CONTENTS)
which will (shallow) copy the existing class default dictionary to initialize the instance.
Upvotes: 2