0

Here's my attempt at grabbing the dictionary:

pairs = {'EMOTIONS': ['happy', 'angry', 'sad', 'calm'], 'TRAITS': ['impatient', 'persistent', 'meek']}

And turning it into a dictionary whose values are written as a phrase, so that:

pairs = {'EMOTIONS': ['I am happy', 'I am angry', 'I am sad', 'I am calm'], 'TRAITS': ['I am impatient', 'I am persistent', 'I am stubborn']} 

Here's the code so far:

pairs = {'EMOTIONS': ['happy', 'angry', 'sad', 'calm'], 'TRAITS': ['impatient', 'persistent', 'meek']}
I_am = 'I am '

for title, words in pairs.items():
    words = [I_am+word for word in words]

I'm obviously doing something wrong because when I request print(pairs), it returns the exact same dictionary I began with. What do I change to make this work?

BorisAdasson
  • 105
  • 5

4 Answers4

0

Try creating a new dictionary and writing to that in the for loop:

modpairs = {}
for title, words in pairs.items():
    words = [I_am+word for word in words]
    modpairs[title] = words
print(modpairs)
AbbeGijly
  • 1,191
  • 1
  • 4
  • 5
  • You could modify the values in-place in `pairs` but modifying a dictionary while iterating over its items is not a good general practice. – AbbeGijly Apr 29 '20 at 13:18
0

Make sure to mutate the list, not just rebind the loop variable:

for words in pairs.values():
    words[:] = [I_am + word for word in words]
    # or, if you want to be fancy
    words[:] = map(I_am.__add__, words)

This uses slice assignment to change the list object.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Using single for loop.

    pairs = {'EMOTIONS': ['happy', 'angry', 'sad', 'calm'], 'TRAITS': ['impatient', 'persistent', 'meek']}
    dic = {}
    for x,y in pairs.items():dic[x]=list(map(lambda x:'I am '+x,y))
    print(dic)
Sachin Gupta
  • 186
  • 1
  • 14
0

When you say

    words = [I_am+word for word in words]

you create a new list with the prefix you are looking for, and assign that list to the local variable words, but you do not change the dict's value in any way. To achieve that, this should work:

new_pairs = {key: [I_am + adjective for adjective in pairs[key]] for key in pairs}
revilovs
  • 61
  • 2
  • 4