Reputation: 17
google = {
'Pixel 4' : 64000,
'Pixel 3' : 54000,
'Pixel 2' : 42000,
'Pixel' : 25000
}
iPhone = {
'11' : 95000,
'X' : 80000,
'7S' : 70000,
'7' : 42000
}
print("Mobile Brand = google, iphone")
print(f"{google} \n{iPhone}")
print("Please write the name of brand as mentioned in list")
m = input("Which mobile company do you like? ")
'''Here, if user inputs google then it will be initiated as 'google' in the memory '''
n = str(input(f"Which model of {m} you want to buy? ")) # user inputs Pixel 4
m1 = m.replace("'", "") #Here I'm trying to make 'google' as google to use it for next variable
print(f"The price of {n} :", m1[n])
''' Here the value should be as google['Pixel 4'] and value should print 64000 but it gives type error because m1[n] is assumed as 'google'['Pixel 4']. Is there any way to initialized 'google''s to google only? '''
print(f"The price of {n} :", m1[n])
If I use print(f"The price of {n} :", google[n]) then the program works fine.
This is the error... TypeError: string indices must be an integer Please help me!!!
Upvotes: 0
Views: 77
Reputation: 14233
That is perfect example why you should keep data/info away from names. The proper way to do this is to have proper data structure.
brands = {'google':{
'Pixel 4' : 64000,
'Pixel 3' : 54000,
'Pixel 2' : 42000,
'Pixel' : 25000
},
'iphone':{
'11' : 95000,
'X' : 80000,
'7S' : 70000,
'7' : 42000
}}
brand = input(f"Which mobile company do you like: {','.join(brands.keys())}?").lower()
model = (input(f"Which model you want to buy: {','.join(brands[brand].keys())}? "))
print(f"The price of {model} is {brands[brand][model]}")
output
Which mobile company do you like: google,iphone?google
Which model you want to buy: Pixel 4,Pixel 3,Pixel 2,Pixel? Pixel
The price of Pixel is 25000
Upvotes: 4
Reputation: 1055
You need to retrieve the model from the chosen brand dictionary.
print(f"The price of {n} :", globals()[m1][n])
Upvotes: 1