My goal is to extract an element from many list that similar like this. Taking elements that is food.
test_list =
['Tools: Pen',
'Food: Sandwich',
'Fruit: Apple'
]
I the final result would be "Sandwich" by look list element with the word "Food:" and split from there.
My usual method is lookup by index
test_list[1].split(': ')[1]
However, I go through many lists that number of elements is varied, and I want to look up the food item in the "food:" section. I don't know if there is a function that would help me choose element from a list using "keyword search"
Another example,
test_list_2 =
['Tools: Pen',
'Tree: Willow'
'Food: Drumstick',
'Fruit: Apple'
]
With the same lines of code, test_list_2 result would be "Drumstick"
Please kindly help my find a way to do that in Python. Thank you
CodePudding user response:
I would consider using a dictionary for this application.
to translate a list of the form you gave into a dictionary:
test_dict = {i.split(": ")[0]: i.split(": ")[1] for i in test_list}
And then you can access elements by key
test_dict['Food']
CodePudding user response:
What you want is a dictionary.
test_list_2 =
{'Tools': 'Pen',
'Tree': 'Willow',
'Food': 'Drumstick',
'Fruit': 'Apple'
}
print(test_list_2["Tools"])