SamChancer
SamChancer

Reputation: 75

Modifying a value in a Python dictionary

I have a dictionary called Basket #of fruit. For reasons, Basket looks like this..

Basket = {
          Fruit1 : "none"
          Fruit2 : "none"
          Fruit3 : "none"
          Fruit4 : "none"
          Fruit5 : "none"
         }

I'd like to check if Apple is in this dictionary, and if it is not- to enter it as Fruit1. But lets say the Basket has been accessed already somehow and Banana has already been set as Fruit1, then I'd like Apple to be set as Fruit2 instead, but if Pear is already in there than it should be Fruit3 and so on. My overall code is... not the best, but at this point this is the way it must work if it is to work, so short of scrapping what is in place already (I hope to revise it all later) how can I make this work?

At the moment the rest of the code simply checks if Fruit1 == Apple and if not moves on to compare Fruit2 etc, if it finds a match then it does stuff but if there is no Apple already in Basket then Apple will never be added, and all keys in the Basket are initially set to "none". I've perplexadoxed myself. Any advise appreciated!

Upvotes: 1

Views: 100

Answers (2)

Simon
Simon

Reputation: 10158

I believe something like this will work. There are probably more efficient ways to do it though:

Basket = {
          'Fruit1' : "none",
          'Fruit2' : "none",
          'Fruit3' : "none",
          'Fruit4' : "none",
          'Fruit5' : "none"
         }

basketSize = len(Basket)

if 'apple' not in Basket.values():
    print "Couldn't find the apple"

    for i in range(basketSize):
        curItem = "Fruit"+str(i+1)
        if Basket[curItem] == "none":
            Basket[curItem] = "apple"
            break

print Basket

Upvotes: 1

Mike P
Mike P

Reputation: 752

The following statement:

'apple' in Basket.values()

will return True if 'apple' is one of the values in the dictionary.

Basket.values().index('apple')

returns the index of 'apple'. If 'apple' isn't in the dictionary, you get a ValueError exception.

If you get a ValueError exception, add 'apple' as the 'Fruit1' value; otherwise, use the index to set the correct FruitN value:

index = Basket.values().index('apple')
key, value = Basket.items()[index]
value = 'banana'
Basket[key] = value

Note, the above snippet shows how to replace an existing value of 'apple' with 'banana'; it doesn't show the exception handling in case 'apple' isn't in the dictionary. However, it should be enough to get you moving.

Upvotes: 2

Related Questions