0

I have the following python script

def main():
    json_obj = {
        "attributes": [
            {
                "key": "some key",
                "value": "hello"
            }
        ]
    }

    needle = "hello"
    if needle in json_obj["attributes"]:
        print("yay")


if __name__ == "__main__":
    main()

Now i don't understand why the print statement returns false. surely needle is in the list.

santino98
  • 145
  • 1
  • 2
  • 9

1 Answers1

0

This is probably a duplicate but you are doing an in check in a dictionary which on default only checks the keys:

"key" in  {"key": "some key", "value": "hello"}

will yield false since it is similar to:

"key" in  {"key": "some key", "value": "hello"}.keys()

whereas

"hello" in  {"key": "some key", "value": "hello"}.values()

will yield True

dosas
  • 567
  • 4
  • 18
  • `json_obj["attributes"]` is a list of dict. – ekhumoro May 12 '21 at 09:42
  • ... so there are two errors and you would require an additional check – dosas May 12 '21 at 09:43
  • 1
    as @ekhumoro said - correct check is `if needle in json_obj["attributes"][0].values()` – Crunchie May 12 '21 at 09:45
  • @Crunchie The question is ill-defined. Is the search really for ***any*** value that equals `needle`? It seems more likely that the OP wants to find the element for which "value" equals `needle`. – ekhumoro May 12 '21 at 09:54