Reputation: 1267
I am initializing a dictionary of empty lists. Is there a more efficient method of initializing the dictionary than the following?
dictLists = {}
dictLists['xcg'] = []
dictLists['bsd'] = []
dictLists['ghf'] = []
dictLists['cda'] = []
...
Is there a way I do not have to write dictLists each time, or is this unavoidable?
Upvotes: 0
Views: 8683
Reputation: 34718
You can use collections.defaultdict it allows you to set a factory method that returns specific values on missing keys.
a = collections.defaultdict(list)
Edit:
Here are my keys
b = ['a', 'b','c','d','e']
Now here is me using the "predefined keys"
for key in b:
a[key].append(33)
Upvotes: 8
Reputation: 1124110
If you adding static keys, why not just directly put them in the dict constructor?
dictLists = dict(xcg=[], bsd=[], ghf=[])
or, if your keys are not always also valid python identifiers:
dictLists = {'xcg': [], 'bsd': [], 'ghf': []}
If, on the other hand, your keys are not static or easily stored in a sequence, looping over the keys could be more efficient if there are a lot of them. The following example still types out the keys
variable making this no more efficient than the above methods, but if keys
were generated in some way this could be more efficient:
keys = ['xcg', 'bsd', 'ghf', …]
dictLists = {key: [] for key in keys}
Upvotes: 4
Reputation: 21089
In the versions of Python that support dictionary comprehensions (Python 2.7+):
dictLists = {listKey: list() for listKey in listKeys}
Upvotes: 1
Reputation: 363787
If the keys are known in advance, you can do
dictLists = dict((key, []) for key in ["xcg", "bsd", ...])
Or, in Python >=2.7:
dictLists = {key: [] for key in ["xcg", "bsd", ...]}
Upvotes: 7
Reputation: 13758
You can also use a for loop for the keys to add:
for i in ("xcg", "bsd", "ghf", "cda"):
dictList[i] = []
Upvotes: 2