The following code takes two inputs, item_name
and sale_type
. It will look through item_dict
to find if any keys that contain part of the item_name
or fully matches it and output the values.
I am trying to convert the following for loop
into a list comprehension. I am fairly comfortable with the basic list comprehensions but in this case I require the text to be split and obtain the relevant results. I am not sure if what I am asking for is possible.
item_name = "GalaxyDevices"
sale_type = "buy"
item_dict = {"buy_Galaxy": [11111, 2232], "sell_Galaxy": [2111]}
results = []
for key, value in item_dict.items():
key = key.split("_")
if key[0] != sale_type:
continue
if key[1] in item_name:
results.extend(value)
print(results)
input / output:
item_name = "GalaxyDevices"
sale_type = "buy"
>>> [11111, 2232]
My failed attempt:
results = [value.split("_") for key, value in item_dict.items()]
Many thanks!