字典最新

时间:2016-02-12 07:09:01

标签: python python-2.7 dictionary

这是我的剧本......

shop = ["Apple" , "orange", "mangoo" , "Tomato" , "grape"]
dict = {}
#List Shop

x = """
1. apple
2. orange
3. mangoo
4. tomato
5. grape """
print x
#Screen showing in monitor

while True:

    buy = int(raw_input('what do u want to buy?" (use number 1-7): '))
    buy = shop[buy-1]
    print "You want" , buy
    equal = int(raw_input('how much? : '))
    bb = {buy:equal}
    dict.update(bb)
    print dict, x

如果我选择了相同的订单。旧值将随最新值而变化......

我想要这样做,就像这样...

我选择“Apple”,我想买“3”

在下一个命令中我想再次购买“Apple”

但我会买“6”。 对于苹果来说如此平等就是“9”......

注意:python 2.7,此方法不使用zip,def,return和break选项。

1 个答案:

答案 0 :(得分:2)

注意:dict是字典的保留关键字。使用像my_dict这样的东西。

试试这个:

my_dict[buy] = my_dict.get(buy, 0) + equal

dict.get的语法:

dict.get(key[,default])

代码:

shop = ["Apple" , "orange", "mangoo" , "Tomato" , "grape"]
my_dict = {}
#List Shop

x = """
1. apple
2. orange
3. mangoo
4. tomato
5. grape """
print x
#Screen showing in monitor

while True:    
    buy = int(raw_input('what do u want to buy?" (use number 1-7): '))
    buy = shop[buy-1]
    print "You want" , buy
    equal = int(raw_input('how much? : '))
    my_dict[buy] = my_dict.get(buy, 0) + equal
    print my_dict, x