【问题标题】:How to put both a key and its value from a dictionary through a function如何通过函数将字典中的键及其值放在一起
【发布时间】:2020-06-19 17:44:42
【问题描述】:

我很好奇如何通过函数将字典中的键及其值放在一起。 以下代码是我正在尝试做的一个示例:

dictionary: {
    'apple': 1,
    'pear': 2,
    'strawberry': 3
}

def my_function(fruit, num):
    print(fruit)
    print(num)

【问题讨论】:

  • 你尝试过什么,它到底有什么问题?你知道如何调用函数吗?如何访问字典中的值?
  • 您的函数不清楚:在打印它们之前,它将键和值都作为参数。我不认为那是你想要做的......
  • @JaredWilber - 为什么不呢?处理键/值对很常见。可能只是打印,也可能这只是一个简单的例子。

标签: python python-3.x function dictionary key-value


【解决方案1】:

该函数打印有关键/值对的信息。 dict.items 迭代键/值对。
看起来很不错。

dictionary = {
    'apple': 1,
    'pear': 2,
    'strawberry': 3
}

def my_function(fruit, num):
    print(fruit)
    print(num)

for fruit, num in dictionary.items():
    my_function(fruit, num)

【讨论】:

    【解决方案2】:

    你可以使用dict.keys():

    dictionary = {
        'apple': 1,
        'pear': 2,
        'strawberry': 3
    }
    
    def my_function(fruit, num):
        print(fruit,end=' ')
        print(num)
    
    for fruit in dictionary.keys():
        my_function(fruit, dictionary[fruit])
    

    输出:

    apple 1
    pear 2
    strawberry 3
    

    【讨论】:

      【解决方案3】:

      你的代码有一个错误,你应该使用=而不是:来分配字典。

      您可以将dictionary 传递给函数:

      dictionary = {
          'apple': 1,
          'pear': 2,
          'strawberry': 3
      }
      
      def my_function(key, value):
          print(key, value)
      
      for key, value in dictionary.items():
          my_function(key, value)
      

      【讨论】:

        【解决方案4】:

        首先,我想提请您注意,您在字典中添加键值时错误地使用了':' 而不是'='(第一行)

        现在,让我们进入正题,有几种方法可以解决它,例如dict.items(),如下:

        方法一:

        def myDict(dict):
            for fruit , num in dict.items(): #dict.item(), returns keys & val to Fruit& num 
            print(fruit+" : "+str(num))   # str(num) is used to concatenate string to string.
        
        
        dict = {'apple':1,'pear':2,'strawberry':3}         
        res = myDict(dict)
        print(res)                              *#result showing*
        
        **OUTPUT :**
        
        apple : 1 
        pear : 2 
        strawberry : 3
        

        方法:2

        dictionary = {
            'apple': 1,
            'pear': 2,
            'strawberry': 3 }
        
        def MyDict(key,value):
           print (key+" : "+str(value))   # str(num) is used to concatenate string to string.
        
        for fruits , nums in dictionary.items():
            MyDict(fruits,nums)                   # calling function in a loop
        
            OUTPUT :
            apple : 1
            pear : 2
            strawberry : 3
        

        我希望,这会帮助你.. 谢谢

        【讨论】:

          猜你喜欢
          • 2021-07-21
          • 2021-04-29
          • 2021-12-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-23
          • 2018-04-16
          • 2015-07-07
          • 1970-01-01
          相关资源
          最近更新 更多