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

2024-06-16 12:05:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数,它接受一个字典作为输入并返回一个新字典。在新字典中,我想使用与旧字典相同的键,但我有了新的值。你知道吗

这是我的旧字典:

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

该函数只打印最后一个键和最后一个值,我希望它打印整个字典。你知道吗

有人能解释一下吗?你知道吗


Tags: key函数innewfordictionary字典value
3条回答

你可以在一条线上完成整件事。你知道吗

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

对于demo,如果我用len替换bandit_language函数。你知道吗

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

每次通过循环时,你都要重新初始化一个空白字典。你知道吗

这应该起作用:

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

通过使用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']}

相关问题 更多 >