Home > Blockchain >  Check if json dict have key with exact value
Check if json dict have key with exact value

Time:12-12

data = {
  "matches":[
    {"match1": {
      {"Oddid":1, "Odd":1.7},
      {"Oddid":2, "Odd":2.4},
      {"Oddid":3,"Odd":5.1}
    }
  },
    {"match2": {
      {"Oddid":1, "Odd":2.3},
      {"Oddid":2, "Odd":1.9},
      {"Oddid":3,"Odd":1.2}
    }
  },
    {"match3": {
      {"Oddid":1, "Odd":2.7},
      {"Oddid":2, "Odd":4.6},
      {"Oddid":4,"Odd":9.9}
    }
  }
  ]
}

How can I check if every match has "OddId":4. If it has, i want to print "Odd" value, if it doesen't, i want to print "1.00" Thanks!

CodePudding user response:

you can use two for loop and iterate in data['matches'] and check the condition.

if key['Oddid'] == 4:
    print("Odd")
else:
    print("1.00")

for iterate in a dict that you don't know the keys names this way you can use:

dictname = {"match2": {}, "match1": {}}
for key, value in dictname.items():

note: i think your json have one problem, you have one dict without key and value and for this reason i could not write the code.

CodePudding user response:

Your data is not in the correct format because some of the brackets define a set that includes dictionaries but since dictionaries are unhashable, it gives an error. But after fixing some of the brackets, when can iterate over data to print the desired output:

data = {
  "matches":{
    "match1": [
      {"Oddid":1, "Odd":1.7},
      {"Oddid":2, "Odd":2.4},
      {"Oddid":3, "Odd":5.1}
    ]
  ,
    "match2": [
      {"Oddid":1, "Odd":2.3},
      {"Oddid":2, "Odd":1.9},
      {"Oddid":3,"Odd":1.2}
    ]
  ,
    "match3": [
      {"Oddid":1, "Odd":2.7},
      {"Oddid":2, "Odd":4.6},
      {"Oddid":4,"Odd":9.9}
   ]
  }
}

for dct in data.values():
    for k, lst in dct.items():
        odd = [d['Odd'] for d in lst if d['Oddid']==4]
        if len(odd) > 0:
            print('{}: {}'.format(k,odd[0]))
        else:
            print('{}: 1.00'.format(k))

Output:

match1: 1.00
match2: 1.00
match3: 9.9
  • Related