Python dict how to create a key or add an element to a key?

I am new to Python. I am not only studying its functions, types, etc., but I am also trying to learn pythonic ways of doing things, and therefore my question is:

I have an empty dictionary. Name: dict_x It must have keys whose values ​​are lists.

In a separate iteration, I get the key (ex: key_123 ) and the element (tuple) that needs to be put in the dict_x list the value key_123 .

If this key already exists, I want to add this item. If this key does not exist, I want to create it with an empty list, and then add to it or just create it with a tuple in it.

In the future, when this key appears again, since it exists, I want the value to be added again.

My code consists of this:

Get the key and value.

See if < no key <<20> exists.

and if you don’t create it: dict_x[key] == []

Then: dict_x[key].append(value)

Is this a way to do this? Should I use try/except blocks?

+71
python dictionary
Oct 16
source share
4 answers

Use dict.setdefault() :

 dic.setdefault(key,[]).append(value) 

help (dict.setdefault)

  setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D 
+118
Oct 16
source share

Here are some ways to do this so that you can compare how it looks and choose what you like. I ordered them in a way that, in my opinion, is the most β€œpythonic,” and commented on the pros and cons, which may not be obvious at first glance:

Using collections.defaultdict :

 import collections dict_x = collections.defaultdict(list) ... dict_x[key].append(value) 

Pros: Probably the best performance. Cons: not available in Python 2.4.x.

Using dict().setdefault() :

 dict_x = {} ... dict_x.setdefault(key, []).append(value) 

Cons: Inefficient creation of unused list() s.

Using try ... except :

 dict_x = {} ... try: values = dict_x[key] except KeyError: values = dict_x[key] = [] values.append(value) 

Or:

 try: dict_x[key].append(value) except KeyError: dict_x[key] = [value] 
+26
Oct 16 '12 at 1:19
source share

You can use defaultdict in collections .

Example from doc doc:

 s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = defaultdict(list) for k, v in s: d[k].append(v) 
+7
Oct 16
source share

You can use defaultdict for this .

 d = defaultdict(list) d['key'].append('mykey') 

This is slightly more efficient than setdefault , since you are not creating new lists that you are not using. Each setdefault call is about to create a new list, even if the item already exists in the dictionary.

+5
Oct. 16
source share



All Articles