Home > database >  How to get Json key name if its value is equal to "x" - Python
How to get Json key name if its value is equal to "x" - Python

Time:11-22

I am working on a python practice, it is about trying to check the availability of products in a json file, the condition is that if Key is equal to 1, then it means that producs is available, so if the product is available, then print key names. The Json format looks like:

product={"FooBox": "1", "ZeroB": "0", "Birk": "1", "pjy": "0", "dimbo": "1"}

I would like to get something like following: Acording to preview file, if Key value is "1" then return Key Name, like following:

"Foobox","Birk","dimbo"

Could someone help me to explain how I can get this working?

I tried using somethink like:

product='["FooBox": "1", "ZeroB": "0", "Birk": "1", "pjy": "0", "dimbo": "1"]'
for x in product:
   if x=="1":
      print(x)
   else:
      print("Not Available")

But is output is just the number "1" not the key name, which is what I require.

CodePudding user response:

In your attempted solution product is a string, not a dictionary like you showed in the first snippet.

And even if it were a dictionary, for x in product: would set x to the keys, not the values.

Use product.items() to iterate over the keys and values of the dictionary. Then you can check the value and collect the key.

product={"FooBox": "1", "ZeroB": "0", "Birk": "1", "pjy": "0", "dimbo": "1"}

available = [name for name, avail in product.items() if avail == "1"]
print(available)

CodePudding user response:

stuff = [k for k,v in product.items() if v=="1"] print(stuff)

CodePudding user response:

for key,value in product.items():
    if value == "1":
        print(key)
  • Related