skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search