Marwan Mohamed
Marwan Mohamed

Reputation: 13

Python Dictionaries with lists from user input how to solve this?

Write a program that ask the user to enter an integer representing the number of items to be added to the stock. For these items, the program should then ask for the item barcode number and name, add them to a dictionary and print them.

Why is my code not working as expected?

size=input("Enter size of list")
names=[input()]
code=[int(input())]
for i in size:
    print("Enter name and code")
    names.append(input())
    code.append(int(input()))
    dict={names[i]:code[i]}

print(dict)

Upvotes: 0

Views: 4953

Answers (1)

jpp
jpp

Reputation: 164693

This a functioning version of your code:

size = input("Enter size of list")
names = []
code = []

for i in range(int(size)):
    print("Enter name and code")
    names.append(input())
    code.append(int(input()))

d = dict(zip(names, code))
print(d)

Among the errors that needed fixing:

  • Only use input() in your for loop when you need the data.
  • i needs to cycle through range(int(size)) rather than a string input.
  • Create the dictionary from your lists at the end via zip.
  • Do not name variables after classes, e.g. use d instead of dict.

Upvotes: 3

Related Questions