Suppose we have a List of dictionary items like this below:-
items_list = [{message:Hello There!, name: Smriti, ts:123456}, {message:Hello There!,name: Simran, ts:56789},{message:Heya, name: Pankhuri, ts:897652}]
If regex "Hello" in message[value] then store ts[val] in a list. So my output should be : list of items with ts[val] only if it matches the message[val] to regex "Hello"
Output_list = [ 123456, 56789]
I have tried the following way as shown in below code :
import re
items_list = [{"message":"Hello There!", "name": "Smriti", "ts":123456},{"message":"Hello There!","name": "Simran", "ts":56789},{"message":"Heya"," name": "Pankhuri", "ts":897652}]
data = []
for item in items_list:
if re.match(".*Hello", item['message']):
data.append(item)
data_ts = [item['ts'] for item in data]
print(data_ts)
Is there any better way of doing this ? Appreciate for any good suggestions.
CodePudding user response:
as you said in the comments:
but I think it looks a more complex so thought if there is any better way of doing that.
The easiest way to achieve your goal without using regex:
items_list = [{"message":"Hello There!", "name": "Smriti", "ts":123456}, {"message":"Hello There!","name": "Simran", "ts":56789},{"message":"Heya", "name": "Pankhuri", "ts":897652}]
data_ts = [item['ts'] for item in items_list if "Hello" in item['message']]
print(data_ts)
This gives me:
[123456, 56789]
Additional Note:
And if you want to get rid of case sensitivity, You can use .upper()
like this:
data_ts = [item['ts'] for item in items_list if "Hello".upper() in item['message'].upper()]
CodePudding user response:
You could do this
items_list = [{"message":"Hello There!", "name": "Smriti", "ts":123456},{"message":"Hello There!","name": "Simran", "ts":56789},{"message":"Heya"," name": "Pankhuri", "ts":897652}]
result = [item["ts"] for item in items_list if re.match(".*Hello", item["message"])]
print(result)