简体   繁体   中英

Python: convert list of tuples (1 to many relationship) to dictionary

I'm trying to convert a list of tuples into a dictionary-dictionary format, however, i could only get a dictionary-list format. May i know how am i able to do it. Thanks in advance.

words = [('food', 'apple'), ('food', 'banana'), ('food', 'pear'),
         ('animal', 'monkey'), ('animal', 'gorilla'), ('animal', 'horse'), 
         ('country', 'UK'), ('country', 'US'), ('country', 'JP')]

dict1 ={}
for k,v in words: 
        if k in dict1:
            dict1[k].append(v)
        else:
            dict1[k]=[v]
        
print (dict1)

Output:

{'food': ['apple', 'banana', 'pear'], 
'animal': ['monkey', 'gorilla', 'horse'],
 'country': ['UK', 'US', 'JP']}

Desired output:

{'food': {'apple', 'banana', 'pear'}, 
'animal': {'monkey', 'gorilla', 'horse'}, 
'country': {'UK', 'US', 'JP'}}

To create the dictionary with set values that you are showing as desired output, you can do the following, utilizing dict.setdefault :

dict1 = {}
for k, v in words: 
    dict1.setdefault(k, set()).add(v)

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