python – How to turn a list of lists of word pairs into a dictionary?

Question:

For example

lst = [['pen','table'],['pen','apple'],['table','morning']]

So what exactly do I need to do? And I need each element of the list of lists to become a key to the list of elements with which it is paired.

lst = {'pen': ['table','apple'], 'table': ['pen','morning'], 'apple': ['pen'], 'morning': ['table']}

Answer:

In such cases it is convenient to use collections.defaultdict :

from collections import defaultdict

d = defaultdict(list)
for a, b in lst:
    d[a].append(b)
    d[b].append(a)

defaultdict by itself works like a dictionary, but if you need the exact type, you can call dict(d) .

Result

{'apple': ['pen'],
 'morning': ['table'],
 'pen': ['table', 'apple'],
 'table': ['pen', 'morning']}
Scroll to Top