簡體   English   中英

Python:將元組列表(一對多關系)轉換為字典

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

我正在嘗試將元組列表轉換為字典字典格式,但是,我只能得到字典列表格式。 我可以知道我怎么能做到這一點。 提前致謝。

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

所需的 output:

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

要使用您根據需要顯示的 output 的設置值創建字典,您可以使用dict.setdefault執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM