How to create key or append an element to key?

PythonDictionary

Python Problem Overview


I have an empty dictionary. Name: dict_x It is to have keys of which values are lists.

From a separate iteration, I obtain a key (ex: key_123), and an item (a tuple) to place in the list of dict_x's value key_123.

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

In future when again this key comes up, since it exists, I want the value to be appended again.

My code consists of this:

> Get key and value. > > See if NOT key exists in dict_x. > > and if not create it: dict_x[key] == [] > > Afterwards: dict_x[key].append(value)

Is this the way to do it? Shall I try to use try/except blocks?

Python Solutions


Solution 1 - Python

Use dict.setdefault():

dict.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

Solution 2 - Python

Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably 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]

Solution 3 - Python

You can use a defaultdict for this.

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

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

Solution 4 - Python

You can use defaultdict in collections.

An example from doc:

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

Solution 5 - Python

dictionary['key'] = dictionary.get('key', []) + list_to_append

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilView Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonantakView Answer on Stackoverflow
Solution 3 - PythonNathan VillaescusaView Answer on Stackoverflow
Solution 4 - PythoniMom0View Answer on Stackoverflow
Solution 5 - PythonTomas Silva EbenspergerView Answer on Stackoverflow