Python 3: Convert Tuple to Dictionary

Viewed 72

Trying to Convert this:

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

Into this:

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

Thanks in advance for any and all comments

4 Answers

Here is an approch that you can use,

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)

output:

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

hope this helps you!

Probably you can use .join method on string to convert tuple to string.

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

out_dict = {}

for worditem in word_vomit:
  out_dict[" ".join(worditem[0])] = worditem[1]

print(out_dict)

Here's a concise option using a dictionary comprehension:

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

Output:

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

goal = {}
for key_tuple, value in word_vomit:

    key = " ".join(key_tuple)

    goal[key] = str(value)
Related