Home > other >  Create Key Value pairs from List
Create Key Value pairs from List

Time:06-03

I have the following list:

[('0-N', '3-C'), ('3-C', '5-C'), ('3-C', '9-C'), ('9-C', '12-C')]

I want to create the following dictionary with Key value pair from the list as:

{'0-N':['3-C'],'3-C':['0-N','5-C','9-C'],'9-C':['3-C','12-C'],'12-C':['9-C']}

Any suggestions or help will be highly appreciated.

CodePudding user response:

Use collections.defaultdict:

from collections import defaultdict

lst = [('0-N', '3-C'), ('3-C', '5-C'), ('3-C', '9-C'), ('9-C', '12-C')]

dct = defaultdict(list)
for tup in lst:
    dct[tup[0]].append(tup[1])
    dct[tup[1]].append(tup[0])

dct = dict(dct)
print(dct)
{'0-N': ['3-C'], '3-C': ['0-N', '5-C', '9-C'], '5-C': ['3-C'], '9-C': ['3-C', '12-C'], '12-C': ['9-C']}

CodePudding user response:

You may use built-in function dict.setdefault:

lst = [('0-N', '3-C'), ('3-C', '5-C'), ('3-C', '9-C'), ('9-C', '12-C')]
dct = {}

for a, b in lst:
    dct.setdefault(a, []).append(b)
    dct.setdefault(b, []).append(a)
  • Related