如何在我的字典中存储值

时间:2015-12-04 16:30:20

标签: python list dictionary

包含:

['Item','item','item']

硬币包含:

['Item','Item','Item']

coin_to_bag = {}
print('Here are your bags:\n')
print(bags)
print('\n')
print('Here are your coin types:\n')
print (coins)

我的嵌套循环

bags =  ['small', 'medium','large']
coins = ['quarter', 'dime', 'nickel', 'penny']


'''
what Im trying to do:
foreach bag in bags:
    print: enter in a coin index. e.g. 1 for quarter out of ['quarter', 'dime', 'nickel', 'penny']
    prompt:: how many of this type?         15  (thus will store '15' representing, there are 15 quarters, storing '15')
    for index_position in coins:
        assign index, type = bag            create a dictionary like ["quarter"] = {"1", "15"}}
    print(coin_to_bag)      

'''
for bag in bags:
    coin_to_bag = coin_to_bag[bag]   # set quarter as a key in coin_to_bag = {["quarter"]}
    coin_type = input('Number of this type? e.g. type 1 for Quarter "["Quarter", "Nickel"]" ')  #e.g. 0.25 * 2
    coin_amount = input('Number of this type?   e.g. 15')  #e.g. 0.25 * 2
    for coin in coins:
        #set values for key: quarter like {["quarter"] = ["1", "15"]}
        coin_to_bag[bag] = coin_to_bag[coin_type], coin_to_bag[coin_amount]  

print(coin_to_bag)

我似乎无法弄清楚如何使用我的dictionarylists(coin,bags)

最终我试图让coin_to_bag存储:

coin_to_bag = {"small": {"1", "15"}, "medium": {"2", "5"}  }

1 个答案:

答案 0 :(得分:4)

以这种方式将值存储到字典:

rake assets:precompile

或在一行中:some_dict = {} some_dict[key] = value

所以大概,你想要:

some_dict = {key: value}

例如,这可能意味着,

coin_to_bag[bag] = [coin_type, coin_amount]

执行此操作,coin_to_bag['small'] = ["1", "15"] 表示使用coin_to_bag[bag]指定的密钥访问coin_to_bag字典的元素。但是这个键值在你设置之前不会存在。