I am trying to make a function that converts the currency in a given dict:
q = {
'1': ('tissue', '200', '30USD'),
'2': ('shampoo', '300', '75000RUB'),
'3': ('vaseline', '180', '10USD'),
'5': ('cup', '0', '15USD'),
'4': ('chips', '150', '100USD'),
'6': ('chocolate', '0', '20USD')
}
This is the function i came up with:
def convert_price(q, rate=24000):
prices = []
converted_dict={}
for value in q.values():
l_value=list(value)
target = l_value[2]
new_price = target
if target[-3:] == "RUB":
new_price = str(int(target[:-3])/rate) + "USD"
l_value[2] = new_price
prices.append(new_price)
else:
prices.append(target)
#print(prices)
for price in prices:
for id in q.keys():
new = str(price)
if new in q[id]:
converted_dict[id]=q[id]
break
print(converted_dict)
convert_price(q)
The function above adds the new prices to the "prices" list. But it can’t add the changed price because it couldn’t find the same value witrh the same currency in the dict.
How should I change the code to make it work?
>Solution :
Is this what you need? In your current code converted_dict doesn’t contain key "2" because its price is in Rubel. If you need to add it. Below code will work.
def convert_price(q, rate=24000):
prices = []
converted_dict={}
for value in q.values():
l_value=list(value)
target = l_value[2]
new_price = target
if target[-3:] == "RUB":
new_price = str(int(target[:-3])/rate) + "USD"
l_value[2] = new_price
prices.append(new_price)
else:
prices.append(target)
# print(prices)
for i in range(len(prices)):
id = str(i+1)
temp_list= list(q[id])
temp_list[2] = prices[i]
converted_dict[id] = tuple(temp_list)
print(converted_dict)
convert_price(q)