How to insert user input in a dictionairy - python3 - python

I was supposed to insert new items to a dictionary, and the new items would be decided by the user input. I have tried three differents things (the ones marked as comments), but none is working. Does anyone know how to fix it?
butikk = {"melk": 14.9, "broed": 24.9, "yoghurt": 12.9, "pizza": 39.9}
print(butikk)
ny_vare = str(input("Skriv inn en matvare og prisen: "))
ny_vare_pris = float(input("Hvor mye koster varen? "))
ny_vare1 = str(input("Skriv inn en matvare: "))
ny_vare1_pris = float(input("Hvor mye koster varen? ")
#butikk.append(ny_vare)
#butikk.append(ny_vare1)
#butikk[ny_vare] = ny_vare_pris
#butikk[ny_vare1] = ny_vare1_pris
#butikk.update(ny_vare : ny_vare_pris)
#butikk.update(ny_vare1 : ny_vare1_pris)
print(butikk)

Okay, so your problem is solved. To be noted, you had done 2 things wrong here.
First, you missed a bracket on line 8 and
Second one is that you should apply {} to update the dictionary.
Let me show you the correct code:
butikk = {
"melk": 14.9,
"broed": 24.9,
"yoghurt": 12.9,
"pizza": 39.9
}
ny_vare = input("Skriv inn en matvare og prisen: ")
ny_vare_pris = float(input("Hvor mye koster varen? "))
ny_vare1 = input("Skriv inn en matvare: ")
ny_vare1_pris = float(input("Hvor mye koster varen? "))
butikk.update({ny_vare: ny_vare_pris})
butikk.update({ny_vare1: ny_vare1_pris})
print(butikk)
Now you will get your desired output.

Related

Why does this python code is not translating the words?

why is this python code not working? I can't figure out the problem.
he always print the same word...
woerterbuch = {"He" :" Er", "She" : "Sie", "it":"es", "Hello":"Hallo", "How":"Wie", "Are":"Geht", "You":"Dir"}
wort = input("Geben Sie den zu übersetzenden Satz ein: ")
woerter = wort.split()
uebersetzung_wort = ""
for wort in woerter:
wort = wort.lower()
if wort in woerterbuch:
uebersetzung = woerterbuch[wort]
else:
uebersetzung = wort
uebersetzung_wort = uebersetzung_wort + " " + uebersetzung
print("Die Übersetzung dieses Satzes ist: ", uebersetzung_wort)
The problem is that you lowercase your word here: wort = wort.lower() but the key in your dict are not lowercased.
You can do the following:
woerterbuch = {"He" :" Er", "She" : "Sie", "it":"es", "Hello":"Hallo", "How":"Wie", "Are":"Geht", "You":"Dir"}
woerterbuch_lowered = {key.lower():value for key,value in woerterbuch.items()}
for wort in woerter:
wort = wort.lower()
uebersetzung = woerterbuch_lowered.get(wort,wort)
uebersetzung_wort = uebersetzung_wort + " " + uebersetzung
You have capital letters in woerterbuch but you look for only lower case because of wort = wort.lower(). Try changing woerterbuch to :
woerterbuch = {"he" :" Er", "she" : "Sie", "it":"es", "hello":"Hallo", "how":"Wie", "are":"Geht", "you":"Dir"}
and then it will work correctly.
You convert your words (woerter? ;->) to lowercase with:
wort = wort.lower()
but some keys in your dictionary start with uppercase. Remove the above line and your code should work (despite being unglaublich hässlich)
There are a couple reasons that you'll run into issue translating from a technical perspective. From a linguistic perspective is another question. As Gabip already pointed out, the keys in your dictionary are not lowercased.
In addition to that, you should sanitize your input of punctuation. When I input "Hallo, wie geht es?", neither "Hallo" nor "es" will be translated because your dictionary never gets those as keys. It gets "Hallo," and "es?" which are not keys in your dictionary.

Take a value from a nested list in Python

I ask for a value which is the id of the product.
The thing I want is the price of the product with that id, the last number.
Products code:
producto=[[0, "Patata", "PatataSL", 7], [1, "Jamon", "JamonSL", 21], [2, "Queso", "Quesito Riquito", 5], [3, "Leche", "Muu", 4], [4, "Oro", "Caro", 900], [5, "Zapatos", "Zapatito", 56], [6, "Falda", "Mucha ropa", 34]]
def productos():
respuesta=True
while respuesta:
print ("""
1.Mostrar Productos
2.Salir al menu
""")
respuesta=input("Introduzca la opcion ")
if respuesta=="1":
for r in producto:
for c in r:
print(c, end = " ")
print()
elif respuesta=="2":
import menu
elif respuesta !="":
print("\n No ha introducido un numero del menu")
Shopping code:
import clientes
import productos
def compras():
respuesta=True
while respuesta:
print ("""
1.Comprar
2.Salir al menu
""")
respuesta=input("Introduzca la opcion ")
if respuesta=="1":
i = int(input("Introduzca el id del cliente: "))
if i in (i[0] for i in clientes.cliente):
print("El cliente está en la lista")
else:
print("El cliente no está en la lista")
compras()
p = int(input("Introduzca el id del producto: "))
if p in (p[0] for p in productos.producto):
print("El producto esta en stock")
These are the things I´ve been trying but i get an error code: TypeError: 'int' object is not subscriptable.
for j in productos.producto:
for p in j:
print (str(p[3]))
#print("El producto cuesta: " + str(p[p][3]))
Last part is ok.
else:
print("El producto no esta en stock")
compras()
elif respuesta=="2":
import menu
elif respuesta !="":
print("\n No ha introducido un numero del menu")
you can get the nested item by simply adding an additional set of square brackets, so for 7 in the first nested list is producto[0][3]
You can grab the last element in a list by refering to it as the -1th element.
for productList in producto:
if respuesta == productList[0]:
print('Price:', productList[-1])
I assume that you need to print the price of the product based on the id.
producto=[[0, "Patata", "PatataSL", 7], [1, "Jamon", "JamonSL", 21], [2, "Queso", "Quesito Riquito", 5], [3, "Leche", "Muu", 4], [4, "Oro", "Caro", 900], [5, "Zapatos", "Zapatito", 56], [6, "Falda", "Mucha ropa", 34]]
I assume , index 0 is id and index 3 is Price.
product_id = 0 //user input
for v in producto:
if v[0] == product_id:
print(v[0][3])
you need to give the index of the price
If at all possible, it would be nice to see this type of structured data in a class or named tuple.
That way not only do you gain the benefit of always knowing what you're accessing. But it's very simple to figure out how to access it.
Consider the following code:
class Product():
def __init__(self, amount, name, something, price):
self.amount = amount
self.name = name
self.something = something
self.price = price
producto=[
Product(0, "Patata", "PatataSL", 7), Product(1, "Jamon", "JamonSL", 21),
Product(2, "Queso", "Quesito Riquito", 5), Product(3, "Leche", "Muu", 4),
Product(4, "Oro", "Caro", 900), Product(5, "Zapatos", "Zapatito", 56),
Product(6, "Falda", "Mucha ropa", 34)
]
print(producto[0].price)
It might look like more effort, but if you plan on making a large, even slightly complex program, using nested arrays and non-structured data you will find yourself constantly running into problems like the one your currently encountering.
That said, the answer is:
for j in productos.producto:
print (str(j[3]))
You went one level too deep into your nested array.

How to find what number argument was chosen with the input statement?

The variable or the types and the costs:
pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"
The function to see if the in put has a type of pasta that is in the varaible:
def inventory(pt):
return(pt.title() in pasta_types)
Input:
type = input('What pasta would you like: Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, and Fusilli ')
Calling Function:
have = inventory(type)
How do I find out what number of the argument that was chosen?
Here's an example of doing something like that which builds and uses a dictionary that associates the name of each pasta type with its cost:
pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, " \
"Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"
# Create a dictionary associating (lowercase) pasta name to its (float) cost.
inventory = dict(zip(pasta_types.lower().replace(' ', '').split(','),
map(float, pasta_costs.replace(' ', '').split(','))))
## Display contents of dictionary created.
#from pprint import pprint
#print('inventory dictionary:')
#pprint(inventory)
while True:
pasta_type = input('What pasta would you like: ' + pasta_types + '?: ')
if pasta_type.lower() in inventory:
break # Got a valid response.
else:
print('Sorry, no {!r} in inventory, please try again\n'.format(pasta_type))
continue # Restart loop.
print('{} costs {:.2f}'.format(pasta_type, inventory[pasta_type]))

I am trying to make a code to conjugate verbs in French, but I cannot change the keys ''je'' to ''j ' ''

I am trying to make my code work like this:
Enter a verb in French: chanter
Output 1: je chante
tu chantes
il ou elle chante
nous chantons
vous chantez
ils ou elles chantent
I succeeded in making the part above, but I cannot succeed in switching je to j' when the user enters, for instance: echapper
Enter a verb in French: echapper
Output 2: j'echappe
tu echappes
il ou elle echappe
nous echappons
vous echappez
ils ou elles echappent
Code:
list = {
"je": 'e',
"tu": 'es',
"il ou elle": 'e',
"nous": 'ons',
"vous": 'ez',
"ils ou elles": 'ent'
}
veb = input("")
for key in list:
if veb.endswith('er'):
b = veb[:-2]
print(key, b + list[key])
I do not know how to change the key list['je'] to list['j''] to succeed with the Output 2.
If you use double quotes around j', i.e. "j'", it will work. Also, I recommend not using the name list for your dictionary because 1) it's a dictionary, not a list, and 2) you should avoid using builtin python names for your variables.
Also, looks like that conjugation is treated differently, with "j'" at the beginning and "e" at the end (instead of "er").
dictionary = {"je":"j'","tu":'es',"il ou elle":'e',"nous":
'ons',"vous":'ez',"ils ou elles":'ent'}
veb = input("")
for key in dictionary:
if veb.endswith('er'):
b = veb[:-2]
if key == 'je':
print(key, dictionary[key] + b + 'e')
else:
print(key,b + dictionary[key])
You should just simply replace the print statement with an if statement:
if key == "je" and (veb.startswith("a") or veb.startswith("e") or [etc.]):
print("j'",b + list[key])
else:
print(key,b + list[key])

Python: How do you add a list to a list of lists in python?

I am learning python so this question may be a simple question, I am creating a list of cars and their details in a list as bellow:
car_specs = [("1. Ford Fiesta - Studio", ["3", "54mpg", "Manual", "£9,995"]),
("2. Ford Focous - Studio", ["5", "48mpg", "Manual", "£17,295"]),
("3. Vauxhall Corsa STING", ["3", "53mpg", "Manual", "£8,995"]),
("4. VW Golf - S", ["5", "88mpg", "Manual", "£17,175"])
]
I have then created a part for adding another car as follows:
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))
It isnt working though and comes up with this error:
Would you like to add a new car?(Y/N)Y
What is the name of the new car?test
How many doors does it have?123456
What is the fuel efficency of the new car?23456
What type of gearbox?234567
How much does the new car cost?234567
Traceback (most recent call last):
File "/Users/JagoStrong-Wright/Documents/School Work/Computer Science/car list.py", line 35, in <module>
car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))
TypeError: string indices must be integers
>>>
Anyones help would be greatly appreciated, thanks.
Just append the tuple to the list making sure to separate new_name from the list with a ,:
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.append(("{}. {}".format(len(car_specs) + 1,new_name),[new_doors, new_efficency, new_gearbox, new_price]))
I would use a dict to store the data instead:
car_specs = {'2. Ford Focous - Studio': ['5', '48mpg', 'Manual', '\xc2\xa317,295'], '1. Ford Fiesta - Studio': ['3', '54mpg', 'Manual', '\xc2\xa39,995'], '3. Vauxhall Corsa STING': ['3', '53mpg', 'Manual', '\xc2\xa38,995'], '4. VW Golf - S': ['5', '88mpg', 'Manual', '\xc2\xa317,175']}
Then add new cars using:
car_specs["{}. {}".format(len(car_specs)+1,new_name)] = [new_doors, new_efficency, new_gearbox, new_price]
You are not setting the first element go your tuple correctly. You are appending the name to the length of car specs as you expect.
Also new_name is as string, when you do new_name[x] your asking python for the x+1th character in that string.
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(str(len(car_specs + 1))+'. - ' + name, [new_doors, new_efficency, new_gearbox, new_price])

Categories