Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize defaultdict with keys?

Tags:

I have a dictionary of lists, and it should be initialized with default keys. I guess, the code below is not good (I mean, it works, but I don't feel that it is written in the pythonic way):

d = {'a' : [], 'b' : [], 'c' : []} 

So I want to use something more pythonic like defaultict:

d = defaultdict(list) 

However, every tutorial that I've seen dynamically sets the new keys. But in my case all the keys should be defined from the start. I'm parsing other data structures, and I add values to my dictionary only if specific key in the structure also contains in my dictionary.

How can I set the default keys?

like image 885
Amir Avatar asked Mar 21 '17 04:03

Amir


People also ask

How do you declare a Defaultdict?

A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError .

What does the Defaultdict () function do?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

How does Defaultdict work Defaultdict will automatically?

The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it.

How do you handle missing keys in Python?

Using setdefault() Method to handle KeyError This setdefault() method is similar to the get() method. It also takes two argument like get(). The first one is the key and the second one is default value. The only difference of this method is, when there is a missing key, it will add new keys with default value.


1 Answers

From the comments, I'm assuming you want a dictionary that fits the following conditions:

  1. Is initialized with set of keys with an empty list value for each
  2. Has defaultdict behavior that can initialize an empty list for non-existing keys

@Aaron_lab has the right method, but there's a slightly cleaner way:

d = defaultdict(list,{ k:[] for k in ('a','b','c') }) 
like image 164
rovyko Avatar answered Nov 01 '22 10:11

rovyko