0

I am trying to make a dictionary by getting the item name and the number of items from the user and make them a key,value pair. This is the code I have so far:

groceries={}
item,number=input("Enter item and number").split()

I am trying to make my code as short as possible and do not want to use the for loop. Is there a way to do this by adding one more line to my code? Meaning when I use print(groceries) I want to actually see the dictionary items that I entered. Thank you.

2 Answers 2

1

Simply you can pass item as key in your groceries dict and pass value as number

item,number=input("Enter item and number ").split(' ')

groceries = {}
groceries[item] = number
Sign up to request clarification or add additional context in comments.

1 Comment

What king of input to you expect ? Because using split and unpack in 2 elements, means the input if a 2-word string, then you zip them, so for bar makes {f:b, o:a, r:r} strange
0

If you're using python 3.8 then you can make it even shorter with the walrus operator:

print({(values := input("Enter item and number").split())[0]: values[1]})

If you want to update your existing dictionary:

groceries = {"foo": "bar"}

print({**groceries, **{(values := input("Enter item and number").split())[0]: values[1]}})

2 Comments

That use of the walrus operator, makes the code so unreadable^^ readability should be in the top priorities
I agree but he said "I am trying to make my code as short as possible".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.