Darth Sidius Darth Sidius - 1 year ago 49
Python Question

printing the key and the values when a key has been searched and found in dict

my text file:

45623189 Intel Core i7, 337.71, 10, 5,

63217452 Intel Core i5, 239.58, 10, 5,

14527869 Intel Core i3, 120.89, 10, 5,

85274198 Gigabyte GeForce GTX, 244.86, 10, 5,

32145687 Sapphire AMD Radeon RX, 254.40, 10 5,

98754236 MSI Radeon RX, 265.45, 10, 5,

63874129 ASUS GeForce GTX, 429.00, 10, 5,

My Code:

gtin8 = input("Enter GTIN8 code to serach for: ")

for key, value in d.items():
if gtin8 in d:
print(key[gtin8], "=", value)

print("Product not found")

the output i get:

Enter GTIN8 code to serach for: 98754236
Traceback (most recent call last):
File "GTIN-8.py", line 60, in
print(key[gtin8], "=", value)
TypeError: string indices must be integers

I am trying to find the code in the file and return the key and all its values once found but seem to be stuck at this point. I have tried converting gtin8 variable to an int but still get an error.

Any ideas?


Answer Source

when you take the input the default type is string. so typecast it in integer.

gtin8 = int(gtin8)

EDITED: for your problem just use :

gtin8 = input("Enter GTIN8 code to serach for: ")
if gtin8 in d:
    print "key = ", gtin8,"value = ", d[gtin8]
    print("Product not found")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download