RTME SUPER
RTME SUPER

Reputation: 21

I have to print a dictionary into different lines how do I do what

So I have a code there I need to print the dictionary formed into different lines and It keeps giving my error on the last line I don't know. I'm new to programming so need some help.

    phonebook = {}

    line = input('Name and clour: ')
    while line:
     name, number = line.split()
     phonebook[name] = number    
     line = input('Name and clour: ')
     phonebook.keys()[1]

Here is the error

    Traceback (most recent call last):
    File "program.py", line 9, in <module>
    print(phonebook.keys()[1])
    TypeError: 'dict_keys' object does not support indexing

Upvotes: 0

Views: 60

Answers (2)

Guimoute
Guimoute

Reputation: 4629

Fixing vbhargav875's answer so that the input code is not used twice.

phonebook = {}

while True:
    if not (line := input("Name and colour: ")): # Empty input will exit the loop.
        break
    name, number = line.split(", ") # I'm guessing you want them comma separated.
    phonebook[name] = number
    print(f"Name: {name}, number: {phonebook[name]}.") 

print(phonebook) # In case you want to print the entire dictionary.

Upvotes: 0

vbhargav875
vbhargav875

Reputation: 887

You could try this :

phonebook = {}

line = input('Name and colour: ') #I'm guessing you want them comma separated
while (len(line)>0):
    name, number = line.split(",")
    phonebook[name] = number
    print("Name : ",name," Number : ",phonebook[name])   
    line = input('Name and colour: ')

print(phonebook) # Incase you want to print the entire dictionary

Upvotes: 1

Related Questions