简体   繁体   中英

Dictionary: Python loop through input

So I have this problem that I have been trying to solve for days. The problem runs this way:

You will receive a single line containing some food {keys} and quantities {values}. They will be separated by a single space (the first element is the key, the second - the value, and so on). Create a dictionary with all the keys and values and print it on the console. Sample input: bread 10 butter 4 sugar 9 jam 12 Output: {'bread': 10, 'butter': 4, 'sugar': 9, 'jam': 12}

Here is the code that I've tried but it only shows the first pair on the list:

stocks = {}
stock = input()

stock = stock.split(" ")

stocks[stock[0]] = stocks.get(stock[0],0) + int (stock[1])

for k,v in stocks.items():
    print(f"{k}: {v}")

Console:

bread 10 butter 4 sugar 9 jam 12
bread: 10
1

Can you help me out? I am stumped for ideas. I really dread working with dictionaries on python. Thank you!

You can dict comprehension

stocks = "bread 10 butter 4 sugar 9 jam 12"

elements = stocks.split()
res = {elements[i]: elements[i + 1] for i in range(0, len(elements), 2)}

for key, value in res.items():
    print(key, value)

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