如何通过函数从字典中放入键及其值

How to put both a key and its value from a dictionary through a function

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

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

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

该函数打印有关 key/value 对的信息。 dict.items 迭代 key/value 对。
看起来很般配。

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)

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

您可以将 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)

您可以使用 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

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

现在,让我们进入正题,有几种解决方法,例如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

希望对您有所帮助.. 谢谢