selfteaching
selfteaching

Reputation: 33

Using dictionary on python

I am trying to learn python. Just downloaded the latest version and trying to figure out how to use dictionary if I am not importing the data. If I wanted to have a user enter their first and last name, and how old they are- is there a way to keep asking the user to input the values, and have the dictionary automatically assign a key? for example-

inputs:Homer Simpson, age 43 - Mr. Burns 82, Ned Flanders 43
output: 
1(key) Homer Simpson 43
2 Mr. Burns 82
3 Ned Flanders 43



name=[]
age=[]
dict1=[]

while True:
    lastName=input('Please enter name or done to exit: ')
    age=input('Please enter age: ')
    if lastName!='done':
        dict1.append({string:name+ age})
    else:
        print(dict1)
        break

Upvotes: 1

Views: 51

Answers (1)

user3483203
user3483203

Reputation: 51155

Try this, loops until you don't enter a name, increments the current key each iteration:

dct = {}
i = 1
while(True):
    name = input("Please enter a name: ")
    if name == "":
        break
    age = input("Please enter an age: ")
    dct[i] = {"name": name, "age": age}
    i += 1

print(dct)

Example input/output:

Please enter a name: Chris
Please enter an age: 23
Please enter a name: Daryll
Please enter an age: 22
Please enter a name: 
{1: {'name': 'Chris', 'age': '23'}, 2: {'name': 'Daryll', 'age': '22'}}

Upvotes: 2

Related Questions