Reputation: 57
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)
Upvotes: 0
Views: 1102
Reputation: 1
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
Upvotes: 0
Reputation: 77357
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)
Upvotes: 1
Reputation: 5048
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)
Upvotes: 0
Reputation: 27577
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
Upvotes: 0