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?

+6


source to share


5 answers


This is already sane, but you can shorten it a bit with a dict comprehension that uses a standard list of keys.



>>> standard_keys = ['a', 'b', 'c']
>>> d1 = {key:[] for key in standard_keys}
>>> d2 = {key:[] for key in standard_keys}
>>> ...

      

+5


source


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

+3


source


If you are going to pre-initialize empty lists, there is no need to use defaultdict. Simple dictation makes the job clear and clean:

>>> {k : [] for k in ['a', 'b', 'c']}
{'a': [], 'b': [], 'c': []}

      

+2


source


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]}

+1


source


From the comments, I assume you want a dictionary that meets the following conditions:

  1. Initialized with a set of keys with an empty list value for each
  2. 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') })

      

+1


source







All Articles