Dominique M
Dominique M

Reputation: 305

Adding key and value to a dictionary within a function in python

I'm currently trying to add a new key and value to an empty dictionary by using a function with three variables.

The following is what I have, but it doesn't work...

def add_fruit(inventory, fruit, quantity=0):
    new_inventory = {}
    for key in inventory: 
        new_inventory[fruit] = quantity
    return new_inventory

What do I have to add or change to make this function work properly? For example, if I want to add 10 strawberries I'd say new_inventory["strawberries"] = 10 but in the function I fail to add this to the dictionary.

I would appreciate some help or suggestions!

Thanks in advance

Upvotes: 1

Views: 3353

Answers (3)

Adam Omar
Adam Omar

Reputation: 11

This is how I solved it.

def add_fruit(inventory, fruit, quantity=0):
    inventory[fruit] = quantity
    return inventory
def add_to_fruit(inventory, add_more):
    for key,value in inventory.items():
        if len(inventory) == 1:
            inventory[key] += add_more
        return inventory
            
# make these tests work...
new_inventory = {}
add_fruit(new_inventory, 'strawberries', 10)
#  test that 'strawberries' in new_inventory
print('strawberries' in new_inventory)
#  test that new_inventory['strawberries'] is 10
print(new_inventory)
add_to_fruit(new_inventory, 25)
#  test that new_inventory['strawberries'] is now 35)
print(new_inventory)

Upvotes: 1

jpp
jpp

Reputation: 164703

There are a few ways you can update your dictionary via function:

dict.__setitem__

Simply set an item via setitem or its syntactic sugar []:

def add_fruit(inventory, fruit, quantity=0):
    inventory[fruit] = quantity
    return inventory

dict.update

Create a dictionary and update your existing dictionary with this one:

def add_fruit(inventory, fruit, quantity=0):
    inventory[fruit] = quantity
    return inventory

Create new dictionary

Unpack the existing dictionary while adding a new item, as described by @ArtyonNeustroev.

Upvotes: 0

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

It looks like your problem is that you are adding a new key multiple times (for key in inventory) and don't add other keys from the original dictionary?

I'd suggest you unpack the original dictionary and add a new key like this:

def add_fruit(inventory, fruit, quantity=0):
    return {**inventory, fruit: quantity}

More on python unpacking: https://www.python.org/dev/peps/pep-0448/

Upvotes: 2

Related Questions