0

Part of a script that I am building requires me to map a user input to a list (possible inputs) which is then associated to a key (the result) in a dictionary. I have already manage to obtain the result but I want to know is there a better way that I can go about this?

user_input = "bought"
output = None

input_mapping = {"buy": ["bought", "buys", "purchased"],
                 "sell": ["sold", "sells", "sale"]}

for key, values in input_mapping.items():
    if user_input in values:
        output = key

print(output)

input / output:

user_input = "sale"
>>> sell

user_input = "bought"
>>> buy

Many thanks!

Raymond C.
  • 572
  • 4
  • 24

3 Answers3

2

In this case, keeping the reverse dictionary will yield the best performance. Searching a dictionary is very good, whilst your method requires searching the entire data.

I would build a simple reverse dictionary and use it:

reversed_dictionary = {item[0]: item[1] for sublist in [[(v,k) for v in input_mapping[k]] for k in input_mapping.keys()] for item in sublist}
Amit Yungman
  • 291
  • 2
  • 6
1

It might seem more redundant to have multiple keys point to the same value, but from a peformance aspect, it's more efficient to lookup the key on the dictionary O(1) than the value on the list O(N).

input_mapping = {
  "bought": "buy",
  "buys": "buy",
  "purchased": "buy",
  "sold": "sell",
  "sells": "sell",
  "sale": "sell"
}

user_input = "bought"
output = input_mapping[user_input]
print(output)

Code Output:

buy
solid.py
  • 2,782
  • 5
  • 23
  • 30
1

You should reverse the mapping, going from output -> [input], to a input -> output mapping:

mapping = {
  "bought": "buy", "buys": "buy", "purchased": "buy", "sold": "sell", "sells": "sell",
  "sale": "sell"}
output = mapping[input]

That would be faster and more intuitive. I would prefer your solution, if the data becomes really large. It is a tradeoff.

Markus
  • 309
  • 2
  • 11