Modifying a value in a Python dictionary

时间:2015-11-12 11:58:32

标签: 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!

2 个答案:

答案 0 :(得分:2)

以下声明:

'apple' in Basket.values()
如果'apple'是字典中的值之一,

将返回True。

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

返回'apple'的索引。如果'apple'不在字典中,则会出现ValueError例外。

如果您收到ValueError例外,请将'apple'添加为'Fruit1'值;否则,使用索引设置正确的FruitN值:

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

请注意,上面的代码段显示了如何将'apple'的现有值替换为'banana';如果“apple”不在字典中,它不会显示异常处理。但是,它应该足以让你感动。

答案 1 :(得分:1)

我相信这样的事情会起作用。可能有更有效的方法来做到这一点:

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