0

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!

  • 2
    You specify 0 and 1, so that's what you get. You might want to iterate through it instead, maybe with something like https://stackoverflow.com/questions/312443/how-do-you-split-a-list-or-iterable-into-evenly-sized-chunks – Kenny Ostrom Jan 14 '22 at 01:56
  • 1
    You're only adding the first item from the list to the stocks dictionary. You probably want to loop over your list (stock) to add all of the items. – Eric McKeeth Jan 14 '22 at 01:57
  • Hint: when you want to print every key/value pair, you use a loop, right? Why do you use a loop? When you want to *create* every key/value pair, should you use a loop? Why or why not? – Karl Knechtel Jan 14 '22 at 02:02

1 Answers1

1

You can use 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 dict comprehension part can be rewritten as follows:

res = dict()
for i in range(0, len(elements), 2):
   res[elements[i]] = elements[i + 1]

Josewails
  • 570
  • 3
  • 16