0

I am trying to do a key lookup in python. I have a dictionary of dictionaries If the key exists I am doing a lookup of of the value in the values and returning the key. I want to have a default sets of values in case the key doesn't exist.

I can write a if else statement to check whether the key exist. if the key doesn't exist then I can use the default sets of values.

This is what my dictionary looks like:

lookup= {
        "key1" : {                
                "TRUE"    : ["1"],        
                "FALSE"   : ["0"]                
                },
        "key2": {               
                "TRUE"    : ["d"]               
                },
        "DEFAULT": {      
                "TRUE"    : ["1","t","tr","true"],        
                "FALSE"   : ["0","f","fl","fs","false"]         
            }
        }

This is what I tried:

if __name__ == "__main__":

    item="key1"
    v='0'

    if item in lookup:
        for key, value in lookup[item].items():
            if v.lower() in [x.lower() for x in value]:                     
                v = key
                print(v)

    else:
        for key, value in lookup["DEFAULT"].items():
            if v.lower() in [x.lower() for x in value]:                                           
                v = key
                print(v)  

I was wondering if there is more simpler, intuitive and smarter way of doing this.

Scriddie
  • 2,584
  • 1
  • 10
  • 17
Amit R
  • 101
  • 1
  • 7
  • 1
    https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html – cdarke Jul 03 '19 at 16:18
  • This Stack Overflow post might answer your question: https://stackoverflow.com/questions/9358983/dictionaries-and-default-values – ldtcoop Jul 03 '19 at 16:40
  • why not use get() or except raise KeyError – probat Jul 03 '19 at 16:55

1 Answers1

1

As a partial simplification, you could do:

if __name__ == "__main__":

    item="key1"
    v='0'

    lookup_result = lookup.get(item, lookup["DEFAULT"])
    for key, value in lookup_result.items():
        if v.lower() in [x.lower() for x in value]:
            v = key
            print(v)

Is there any way you can restructure your input data? Needing to go two levels deep and check a list isn't all that optimal.

Jenner Felton
  • 787
  • 1
  • 9
  • 18