Sigsby
Sigsby

Reputation: 57

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

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

Answers (4)

Ravi Ranjan Sagar
Ravi Ranjan Sagar

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:

Method 1st :

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

tdelaney
tdelaney

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

ngShravil.py
ngShravil.py

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

Red
Red

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

Related Questions