简体   繁体   English

如何在字典中存储值

[英]How can i store values in my dictionary

bag contains: 袋子包含:

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

coins contains: 硬币包含:

['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)

my nested loop 我的嵌套循环

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)

I can't seem to figure out how to use my dictionary and lists(coin,bags) 我似乎无法弄清楚如何使用dictionarylists(coin,bags)

Ultimately I'm trying to get coin_to_bag to store: 最终,我试图将coin_to_bag存储:

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

Values are stored to dictionaries in this way: 值通过以下方式存储到字典中:

some_dict = {}
some_dict[key] = value

Or in one line as: some_dict = {key: value} . 或一行为: some_dict = {key: value}

So presumably, you want: 因此,大概您想要:

coin_to_bag[bag] = [coin_type, coin_amount]

For example this might mean, 例如,这可能意味着

coin_to_bag['small'] = ["1", "15"]

Doing this, coin_to_bag[bag] means access the element of the coin_to_bag dictionary with the key given by bag . 这样做, coin_to_bag[bag]意味着使用bag给出的密钥访问coin_to_bag字典的元素。 But that key-value won't exist until you set it. 但是该键值在您进行设置之前不会存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM