简体   繁体   中英

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)

Ultimately I'm trying to get coin_to_bag to store:

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} .

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 . But that key-value won't exist until you set it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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