Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change an item that is a tuple inside a dict

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading