Reputation: 101
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.
Upvotes: 0
Views: 508
Reputation: 807
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.
Upvotes: 1