I'm curious as to how I can put both a key and its value from a dictionary through a function. The following code is an example of what I'm trying to do:
dictionary: {
'apple': 1,
'pear': 2,
'strawberry': 3
}
def my_function(fruit, num):
print(fruit)
print(num)
The function prints information about key/value pairs. dict.items
iterates key/value pairs.
Looks like a great match.
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)
You have one mistake in your code, you should use =
instead of :
for assigning dictionary.
You can just pass the dictionary
to the function:
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)
You can use 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])
Output:
apple 1
pear 2
strawberry 3
At first, i would like to draw your attention that you mistakenly use ':'
instead of '='
while adding keys-values in dictionary. (FIRST LINE)
Now, lets come to the point, there are several ways to solve it such as dict.items()
as follows:
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
METHOD: 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
I hope, this will assist you.. Thankyou
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.