Reputation: 97
I want to write a function that takes in a dictionary as an input and returns a new dictionary. In the new dictionary I would like to use the same keys as in the old one, but I've got new values.
This is my old dictionary:
animals = {'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']
}
Then I'm creating a function that takes in the old dictionary and I want it to keep the keys but change values (the new values should pass through a function called bandit. It looks something like this.
def myfunction(animals):
new_dictionary = {}
for key in animals.keys():
new_dictionary = {key: []}
for value in animals[key]:
bandit_animals = bandit_language(value)
new_dictionary = {key: bandit_animals}
return new_dictionary
print(myfunction(animals))
The function only prints the last key and the last value and I want it to print a whole dictionary.
Can anyone explain?
Upvotes: 4
Views: 148
Reputation: 1921
You could do the whole thing in a single line.
print({k: bandit_language(v) for k, v in animals.items()})
For demo, if I substitute bandit_language
function with len
.
print({k: len(v) for k, v in animals.items()})
Out: {'elephant': 4, 'human': 3, 'tiger': 4}
Upvotes: 0
Reputation: 3974
A more compact way of doing this by using items()
:
animals = {'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']
}
# some dummy function
def bandit_language(val):
return 'Ho ho ho'
def myfunction(animals):
return {key: [bandit_language(val) for val in lst] for key, lst in animals.items()}
print(myfunction(animals)
This produces:
{'human': ['Ho ho ho', 'Ho ho ho', 'Ho ho ho'], 'tiger': ['Ho ho ho', 'Ho ho ho', 'Ho ho ho', 'Ho ho ho'], 'elephant': ['Ho ho ho', 'Ho ho ho', 'Ho ho ho', 'Ho ho ho']}
Upvotes: 0
Reputation: 11657
You're initialising a blank dictionary again at every pass through the loop.
This should work:
def myfunction(animals):
new_dictionary = {}
for key in animals.keys():
new_dictionary[key] = []
for value in animals[key]:
bandit_animals = bandit_language(value)
new_dictionary[key].append(bandit_animals)
return new_dictionary
print(myfunction(animals))
Upvotes: 1