简体   繁体   中英

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.

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

You may use built-in functiondict.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM