Is there a way to look for a part of a string ('USD' in 'USDSEK') in the keys of a dictionary and if found return the value?

Question:

We can model current exchange rates with a provided dictionary

exchange_rates[‘USDSEK’]
10

Use that dictionary to define a method in the class that converts a given currency to the base currency

mca.conversion_rate(‘USD’)
10

#This is the dictionary I’m trying to access

exchange_rates = {'USDSEK': 10, 'EURSEK': 10}

#Here my logic is mostly that if I find the given currency in the key I will return the value of the same key position

def conversion_rate(self, given_currency):
    self.given_currency = given_currency
    for key in exchange_rates.keys():
        if given_currency in exchange_rates.keys():
            er = (exchange_rates[key]).values()
            return er

#Assertion gives the USD currency and according to the dictionary it should be 10

mca = MultiCurrencyAccount('SEK')
assert mca.conversion_rate('USD') == 10, f"{mca.conversion_rate('USD')=} != 10"

#But when I run it it appears the following

AssertionError Traceback (most recent call last)
Input In [193], in <cell line: 2>()
1 mca = MultiCurrencyAccount(‘SEK’)
—-> 2 assert mca.conversion_rate(‘USD’) == 10, f"{mca.conversion_rate(‘USD’)=} != 10"

AssertionError: mca.conversion_rate(‘USD’)=None != 10

Asked By: Grecia Garrido

||

Answers:

If possible, I’d advise you to restructure your data. Have two separate dicts for conversion from and conversion to, and split the string before insertion. This might take more memory, but it will be considerably faster if the database is large enough.

If that’s not possible, you can do this:

for key, value in exchange_rate.items():
    if currency in key:
        return value

(You might use a different comparison like .startswith)

Answered By: Tordek
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.