I have this JSON object
{'result':
{'chk_in': '2022-05-28',
'chk_out': '2022-05-30',
'currency': 'USD',
'rates': [
{'code': 'Expedia', 'name': 'Expedia', 'rate': 299.0, 'tax': 70.0},
{'code': 'BookingCom', 'name': 'Booking.com', 'rate': 299.0, 'tax': 73.0},
{'code': 'CtripTA', 'name': 'Trip.com', 'rate': 297.0, 'tax': 66.0},
],
}
How do I check and get the keys 'code' inside 'rates' contain value 'Expedia'?
This is what I tried but did not succeed.
if ('code','Expedia') in json_object['result']['rates'].items():
print(json_object['result']['rates'])
else:
print('no price')
CodePudding user response:
json_object['result']['rates']
is a list, not a dict, so it doesn't have an items()
method. What you want is something like:
[rate for rate in json_object['result']['rates'] if rate['code'] == 'Expedia']
This will give you a list of all the dictionaries in rates
matching the criteria you're looking for; there might be none, one, or more.
CodePudding user response:
The issue is that the data inside the "rates" key is a list. Take a look at the following:
>>> data = {'result':
{'chk_in': '2022-05-28',
'chk_out': '2022-05-30',
'currency': 'USD',
'rates': [
{'code': 'Expedia', 'name': 'Expedia', 'rate': 299.0, 'tax': 70.0},
{'code': 'BookingCom', 'name': 'Booking.com', 'rate': 299.0, 'tax': 73.0},
{'code': 'CtripTA', 'name': 'Trip.com', 'rate': 297.0, 'tax': 66.0},
],
}}
>>> type(data["result"]["rates"])
<class 'list'>
I'm not sure if I understand what you're trying to do exactly but maybe you are looking for something like this:
>>> data["result"]["rates"]
[{'code': 'Expedia', 'name': 'Expedia', 'rate': 299.0, 'tax': 70.0}, {'code': 'BookingCom', 'name': 'Booking.com', 'rate': 299.0, 'tax': 73.0}, {'code': 'CtripTA', 'name': 'Trip.com', 'rate': 297.0, 'tax': 66.0}]
>>> for rate in data["result"]["rates"]:
... code = rate["code"]
... if code == "Expedia":
... print(rate)
...
{'code': 'Expedia', 'name': 'Expedia', 'rate': 299.0, 'tax': 70.0}
>>>
CodePudding user response:
You want to look through the list of rates and seach the ones with el['code'] == 'Expedia'
:
d = {'result':
{'chk_in': '2022-05-28',
'chk_out': '2022-05-30',
'currency': 'USD',
'rates': [
{'code': 'Expedia', 'name': 'Expedia', 'rate': 299.0, 'tax': 70.0},
{'code': 'BookingCom', 'name': 'Booking.com', 'rate': 299.0, 'tax': 73.0},
{'code': 'CtripTA', 'name': 'Trip.com', 'rate': 297.0, 'tax': 66.0},
],
}
}
print([el for el in d['result']['rates'] if el['code']=='Expedia'])
>>> [{'code': 'Expedia', 'name': 'Expedia', 'rate': 299.0, 'tax': 70.0}]