Python 如何将字典中的键及其值通过函数放入
我很好奇如何通过一个函数把字典中的键和它的值都放进去。 以下代码是我尝试执行的一个示例:Python 如何将字典中的键及其值通过函数放入,python,python-3.x,function,dictionary,key-value,Python,Python 3.x,Function,Dictionary,Key Value,我很好奇如何通过一个函数把字典中的键和它的值都放进去。 以下代码是我尝试执行的一个示例: dictionary: { 'apple': 1, 'pear': 2, 'strawberry': 3 } def my_function(fruit, num): print(fruit) print(num) 该函数打印有关键/值对的信息dict.items迭代键/值对
dictionary: {
'apple': 1,
'pear': 2,
'strawberry': 3
}
def my_function(fruit, num):
print(fruit)
print(num)
该函数打印有关键/值对的信息<代码>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)
您的代码中有一个错误,您应该使用
=
而不是:
来分配字典
您只需将字典
传递给函数:
字典={
"苹果":1,,
"梨":2,,
“草莓”:3
}
def my_功能(键、值):
打印(键、值)
对于键,dictionary.items()中的值:
my_函数(键、值)
您可以使用dict.keys()
:
输出:
apple 1
pear 2
strawberry 3
首先,我想提醒您注意,在字典中添加键值时,您错误地使用了
':'
而不是'='
(第一行)
现在,让我们来谈谈重点,有几种方法可以解决这个问题,例如dict.items()
,如下所示:
方法1:
方法: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
我希望这会对你有所帮助。。
谢谢你试过什么,到底有什么问题?你知道如何调用函数吗?如何从字典中访问值?您的函数不清楚:它将键和值都作为参数,然后再打印它们。我不认为这就是你想做的…@JaredWilber-为什么不?处理键/值对是很常见的。可能只是为了打印,可能这只是一个简单的例子。
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
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