As an additional option without using defaultdict , you can use the dict.setdefault method with a similar effect:
d = {} for a, b in lst: d.setdefault(a, []).append(b) d.setdefault(b, []).append(a)
The setdefault(key, default) method takes the key key , the default value is default and returns the value by the key key . In case there was no such key, it additionally adds the key key with the transmitted value of default . Its approximate code is as follows:
class dict: def setdefault(self, key, default): if key not in self: self[key] = default return self[key]
The disadvantages of this solution are as follows:
- Empty lists are created every time a key is already in the dictionary.
- The
setdefault method has an obscure name.
However, here we are using standard dictionary functionality.
Additionally, if you want to maintain the uniqueness of elements by key (for example, in case pairs can repeat with the same or inverse order), you should use set :
lst = [['pen', 'table'], ['pen', 'apple'], ['apple', 'pen'], ['table', 'morning']] d = {} for a, b in lst: d.setdefault(a, set()).add(b) d.setdefault(b, set()).add(a)
Or, for a solution with defaultdict :
from collections import defaultdict d = defaultdict(set) for a, b in lst: d[a].add(b) d[b].add(a)
In these cases, the d dictionary will look like this:
{'apple': {'pen'}, 'morning': {'table'}, 'pen': {'apple', 'table'}, 'table': {'morning', 'pen'}}
instead
{'apple': ['pen', 'pen'], 'morning': ['table'], 'pen': ['table', 'apple', 'apple'], 'table': ['pen', 'morning']}