I am making a python script with ScratchAttach to automatically answer a certain prompt on my profile, and I have gotten up to the point of getting messages from my profile. Now how do I check if the "Content" key of one of those objects contains the example text "Hello World"? If it wasn't clear, I am doing this in Python.

[{'CommentID': '317977750', 'User': 'shieldroy', 'Content': 'Can you pls advertise my studio and tell people to comment " generic" on my profile.', 'Timestamp': '2024-03-10T04:47:53Z', 'hasReplies?': False}]

I haven't really tried a lot, because I am pretty new to python.

3

There are 3 best solutions below

0
David Waterworth On

You can access key/value pairs in a dict using my_dict['Content'], so you can do

if 'Content' in my_dict and my_dict['Content']=='Hello World':
   print(f"my_dict contains 'Hello World'")

What this does is first check if the key exists in the dictionary, and then checks if the value is the one you want.

An alternative method is

if my_dict.get('Content', default=None)=='Hello World':
   print(f"my_dict contains 'Hello World'")

This makes use of the fact that my_dict.get returns the specified default if the key doesn't exist.

0
Agriseld On

When working with dictionaries, the in operator tests the presence of a key. If the key you are looking for exists, then you can test its value and verify that the key:value pair exists.

array = [{...}]
d = array[0]

if "Content" in d and d["Content"] == "Hello World!":
    # Do something
else:
    # Do something else

Alternatively, you can try to directly get the value at the expected key and catch the error if the key does not exists.

try:
   if d["Content"] == "Hello World!"
        # Do something
except KeyError:
   # Do something else

If you have multiple dictionary in your array, simply repeat the test for each.

0
SIGHUP On

You have a list that contains a single dictionary. The fact that you're using a list implies that it might contain more than one dictionary.

Therefore, what you probably need is something that will check the "Content" key's value in all dictionaries within the list.

The function should return the index of the dictionary that has the relevant content - otherwise return -1 to indicate that nothing was found in any of the dictionaries.

If that's the case then:

from typing import Any

data = [
    {
        "CommentID": "317977750",
        "User": "shieldroy",
        "Content": 'Can you pls advertise my studio and tell people to comment " generic" on my profile.',
        "Timestamp": "2024-03-10T04:47:53Z",
        "hasReplies?": False,
    }
]

def check_content(data: list[dict[str, Any]], s: str) -> int:
    for i, d in enumerate(data):
        if d.get("Content") == s:
            return i
    return -1

print(check_content(data, "Hello world"))