简体   繁体   中英

Write a program that uses a loop to take 3 key-value inputs from the user and create a dictionary using these keys and values

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

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.

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.

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