Sitakanta Satapathy
Sitakanta Satapathy

Reputation: 29

Create Key Value pairs from List

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.

Upvotes: 1

Views: 214

Answers (2)

Mislah
Mislah

Reputation: 308

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)

Upvotes: 2

Timur Shtatland
Timur Shtatland

Reputation: 12347

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']}

Upvotes: 2

Related Questions