How to initialize defaultdict with keys?
I have a dictionary of lists and it needs to be initialized with default keys. I think the code below is not good (I mean, it works, but I don't feel like it is written in a pythonic way):
d = {'a' : [], 'b' : [], 'c' : []}
So, I want to use something more pythonic like defaultict
:
d = defaultdict(list)
However, every tutorial I've seen dynamically sets new keys. But in my case, all keys must be defined from the very beginning. I am parsing other data structures and I only add values ββto the dictionary if my dictionary contains a specific key in the structure.
How do I set the default keys?
source to share
If you have a close set of keys (['a', 'b', 'c'] in your example) you know what you will be using, you can definitely use the answers above.
BUT...
dd = defaultdict(list)
It gives you much more: d = {'a':[], 'b':[], 'c':[]}
. You can append
on "non-existent" keys in defaultdict
:
>>dd['d'].append(5)
>>dd
>>defaultdict(list, {'d': 5})
if you do this:
>>d['d'].append(5) # you'll face KeyError
>>KeyError: 'd'
We recommend doing something like:
>>d = {'a' : [], 'b' : [], 'c' : []}
>>default_d = defaultdict(list, **d)
now you have a key containing your 3 keys: ['a', 'b', 'c'] and empty lists as values, and which you can also add to other keys without explicitly writing: d['new_key'] = []
before adding
source to share
You may have a specific function that will return you dict
with preset keys.
def get_preset_dict(keys=['a','b','c'],values=None):
d = {}
if not values:
values = [[]]*len(keys)
if len(keys)!=len(values):
raise Exception('unequal lenghts')
for index,key in enumerate(keys):
d[key] = values[index]
return d
In [8]: get_preset_dict ()
Out [8]:
{'a': [], 'b': [], 'c': []}
In [18]: get_preset_dict (keys = ['a', 'e', ββ'i', 'o', 'u'])
Out [18]:
{'a': [], 'e': [], 'i': [], 'o': [], 'u': []}
In [19]:
get_preset_dict(keys=['a','e','i','o','u'],values=[[1],[2,2,2],[3],[4,2],[5]])
Conclusion [19]:
{'a': [1], 'e': [2, 2, 2], 'i': [3], 'o': [4, 2], 'u': [5]}
source to share
From the comments, I assume you want a dictionary that meets the following conditions:
- Initialized with a set of keys with an empty list value for each
- Has a default behavior that can initialize an empty list for nonexistent keys
@Aaron_lab has the correct method, but there is a slightly cleaner way:
d = defaultdict(list,{ k:[] for k in ('a','b','c') })
source to share