[英]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: Output:
{'food': ['apple', 'banana', 'pear'],
'animal': ['monkey', 'gorilla', 'horse'],
'country': ['UK', 'US', 'JP']}
Desired output:所需的 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
:要使用您根据需要显示的 output 的设置值创建字典,您可以使用dict.setdefault
执行以下操作:
dict1 = {}
for k, v in words:
dict1.setdefault(k, set()).add(v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.