【问题标题】:Create a function that returns a new dictionary创建一个返回新字典的函数
【发布时间】:2019-01-30 23:08:31
【问题描述】:

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

这是我的旧词典:

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

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

谁能解释一下?

【问题讨论】:

    标签: python python-3.x


    【解决方案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))
    

    【讨论】:

    • 非常感谢!这很有帮助:)
    • 不客气!如果它已关闭,则可以标记为已解决(绿色检查):)
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您可以在一行中完成所有操作。

      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}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-20
        • 1970-01-01
        • 2017-11-23
        • 1970-01-01
        • 1970-01-01
        • 2018-04-23
        相关资源
        最近更新 更多