创建一个返回新字典的函数

时间:2019-01-30 23:08:32

标签: python python-3.x

我想编写一个将字典作为输入并返回新字典的函数。在新词典中,我想使用与旧词典相同的键,但是我有新的值。

这是我的老字典:

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))

该功能仅打印最后一个键和最后一个值,我希望它打印整个字典。

有人可以解释吗?

3 个答案:

答案 0 :(得分:1)

每次循环时,您都要重新初始化空白字典。

这应该有效:

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))

答案 1 :(得分:0)

使用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)

这将产生:

{'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']}

答案 2 :(得分:0)

您可以在一行中完成全部操作。

print({k: bandit_language(v) for k, v in animals.items()})

对于演示,如果我将bandit_language函数替换为len

print({k: len(v) for k, v in animals.items()})
Out: {'elephant': 4, 'human': 3, 'tiger': 4}