我想写一个函数,它接受一个字典作为输入并返回一个新字典。在新字典中,我想使用与旧字典相同的键,但我有了新的值。你知道吗
这是我的旧字典:
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']
}
然后我创建了一个接受旧字典的函数,我希望它保留键但更改值(新值应该通过一个名为bandit的函数)。看起来像这样。你知道吗
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))
该函数只打印最后一个键和最后一个值,我希望它打印整个字典。你知道吗
有人能解释一下吗?你知道吗
你可以在一条线上完成整件事。你知道吗
对于demo,如果我用
len
替换bandit_language
函数。你知道吗每次通过循环时,你都要重新初始化一个空白字典。你知道吗
这应该起作用:
通过使用
items()
更简洁的方法:这将产生:
相关问题 更多 >
编程相关推荐