Carlos
Carlos

Reputation: 61

How to access dictionary values when key isn't exactly the same?

The problem

I have a dictionary like this:

dic = {'9.1':'9.7','10.1':'10.7','11.1':'11.7'}

And I need to access with values in different format:

val_1 = '9.1'
val_2 = '09.1'

If val_1 it's easy to get value:

>>>print(dic[val_1])
>>>9.7

But, in case of val_2 key doesn't exist

Can I use something like this?

dic[float(val_2),key = lambda x: float(x) for x in dic.keys()]

Aditional information

Format in dictionary keys could vary. Examples:

dic = {'9':'9.7'}   
dic = {'9.0':'9.7'}
dic = {'09.0':'9.7'}

Thank you!

Upvotes: 3

Views: 82

Answers (2)

captnsupremo
captnsupremo

Reputation: 730

In the example, you're storing your keys as strings. In that case, the easiest way to remove a leading zero from the val_2 example would be:

val_2.lstrip("0")

You can make this method call on strings that don't have leading zeros as well, with no side effect. So you could do this:

for val in [val_1, val_2]:
    print(dic[val.lstrip("0")])

with output:

9.7
9.7

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140196

You could pre-process your dictionary to have floating point values as keys instead.

Then when you want to access a key, convert to float first.

>>> dic = {'9.1':'9.7','10.1':'10.7','11.1':'11.7'}
>>> dic = {float(k):v for k,v in dic.items()}
>>> dic[float("09.1")]
'9.7'

Of course this can fail because of floating point precision so it's not really a good idea, but this will work if the various forms of writing the value has just a leading or trailing zero, space, ... so the floating point representation of the value will be exactly the same. In the example with 9 written different ways it would work too:

>>> float('09.0') == float('9.0') == float('9')
True

Upvotes: 2

Related Questions