首页 > 解决方案 > Python 3:将元组转换为字典

问题描述

试图转换这个:

word_vomit = [(('best', 'cat', 'breed'), 3), (('dogs', 'wearing', 'hats'), 3), (('did', 'you', 'eat'), 2), (('cats', 'are', 'evil'), 1), (('i', 'hate', 'lists'), 1)]

进入这个:

goal = {'best cat breed': '3','dogs wearing hats': '3','did you eat': '2','cats are evil': '1','i hate lists': '1'}

在此先感谢您的任何和所有评论

标签: pythonpython-3.xdictionarytuples

解决方案


这是您可以使用的方法,

word_vomit = [(('best', 'cat', 'breed'), 3), (('dogs', 'wearing', 'hats'), 3), (('did', 'you', 'eat'), 2), (('cats', 'are', 'evil'), 1), (('i', 'hate', 'lists'), 1)]
dict1={}
for i in word_vomit:
    str1=""
    str1=" ".join(i[0])
    dict1[str1]=str(i[1])
print(dict1)

输出:

{'best cat breed': '3', 'dogs wearing hats': '3', 'did you eat': '2', 'cats are evil': '1', ' i hate lists': '1'}

希望这对你有帮助!


推荐阅读