Reputation: 53
I am new to programming and python and I dont know how to solve this problem.
my_dict = {'tiger': ['claws', 'sharp teeth', 'four legs', 'stripes'],
'elephant': ['trunk', 'four legs', 'big ears', 'gray skin'],
'human': ['two legs', 'funny looking ears', 'a sense of humor']
}
new_dict = {}
for k, v in my_dict.items():
new_v = v + "WOW"
new_dict[k] = new_v
print(new_dict)
I want to make a new dictionary with added phrase but I got an error "can only concatenate list (not "str") to list", but when I am using only one value per key the programme works. Is there any solution to this?
Upvotes: 3
Views: 61
Reputation: 11
With list, you only can concatenate a list only.
#So here you're trying to concatenate a list with the string
my_dict['tiger'] + 'WOW' # this won't work as one is string and other is List.
my_dict['tiger'] + ['WOW'] # this will work as both are of same type and concatenation will happen.
Upvotes: 0
Reputation: 788
You can concatenate a list to another list as follows:
if __name__ == '__main__':
my_dict = {'tiger': ['claws', 'sharp teeth', 'four legs', 'stripes'],
'elephant': ['trunk', 'four legs', 'big ears', 'gray skin'],
'human': ['two legs', 'funny looking ears', 'a sense of humor']
}
new_dict = {}
for k, v in my_dict.items():
new_v = v + ["WOW"]
new_dict[k] = new_v
print(new_dict)
{'tiger': ['claws', 'sharp teeth', 'four legs', 'stripes', 'WOW'], 'elephant': ['trunk', 'four legs', 'big ears', 'gray skin', 'WOW'], 'human': ['two legs', 'funny looking ears', 'a sense of humor', 'WOW']}
Upvotes: 2