Home > database >  Write a program that uses a loop to take 3 key-value inputs from the user and create a dictionary us
Write a program that uses a loop to take 3 key-value inputs from the user and create a dictionary us

Time:01-23

I'm very new to learning programming. I'm starting with Python. Do you know the solution to this problem? That's the closest output I can get...

My attempt:

my_dict={}
for items in range(1,4):
    key=str(input('enter string'))
    value=int(input('enter #'))
    my_dict={f'{key}: {value}'}
    print(my_dict)

output:

{'gregory: 34'}
{'perry: 84'}
{'sinatra: 76'}

Expected Output:

{'gregory': '34', 'perry': '84', 'sinatra': '76'}

I don't know how to get everything on the same line...

CodePudding user response:

my_dict={f'{key}: {value}'}

This creates a brand new dictionary, because you're reassigning the name my_dict.

You don't want this; you want to add this key-value pair to the existing dictionary.

Use this instead:

my_dict[key] = value

And then move the print statatement below the loop.

CodePudding user response:

Oh, I see! Thanks for your help! :)

my_dict={}
for items in range(1,4):
    key=str(input('enter string'))
    value=str(input('enter #'))
    my_dict[key]=value
print(my_dict)

It worked! yay! I also had to make both variables strings to get the quotation marks.

  • Related