How do I replace the json_object's blookup with blookup_values based on the ID's in the json blookup. I tried the below code by removing the ID's which are not present in the json_object['blookup']. The below code doesn't work. Could anyone please help.
blookup_values = [
{
"id":"123",
"name":"abc",
"date":"somedate",
"time":"sometime"
},
{
"id":"456",
"name":"def",
"date":"somedate",
"time":"sometime"
},
{
"id":"789",
"name":"ghi",
"date":"somedate",
"time":"sometime"
},
{
"id":"9999",
"name":"mmmmmm",
"date":"somedate",
"time":"sometime"
},
{
"id":"8888",
"name":"nnnnnn",
"date":"somedate",
"time":"sometime"
}
]
json_object = {
"id":"id_value",
"blookup": [{
"id":"123",
"type":"dddd"
},
{
"id":"456",
"type":"eeeee"
}
]
}
Code
result = [obj for obj in blookup_values if obj['id'] != json_object['blookup']]
Expected result
result = {
"id":"id_value",
"blookup": [{
"id":"123",
"name":"abc",
"date":"somedate",
"time":"sometime"
},
{
"id":"456",
"name":"def",
"date":"somedate",
"time":"sometime"
}
]
}
CodePudding user response:
You have to get the id key from the json_object dictionaries:
result = [obj for obj in blookup_values if obj['id'] in [i["id"] for i in json_object['blookup']]]
CodePudding user response:
First convert blookup_values
into a dictionary keyed by id
. Then you can replace json_object['blookup']
with a list comprehension made from this.
blookup_dict = {value['id']: value for value in blookup_values}
json_object['blookup'] = [blookup_dict[item['id']] for item in json_object['blookup']]
CodePudding user response:
I’m not sure I completely understand what you are trying to do but what I gather is that you want to get the objects in blookup
that do not have any of the same id
s as the objects in json_objects. Is that correct?
Try to first get the id values of each object in json_object['blookup']
. For example:
json_object_ids = [obj['id'] for obj in json_object['blookup']]
Next, filter the objects in blookup
by slightly altering your list comprehension:
result = [obj for obj in blookup_values if obj['id'] not in json_object_ids]
The output would look something like this:
[{'id': '789', 'name': 'ghi', 'date': 'somedate', 'time':
'sometime'}, {'id': '9999', 'name': 'mmmmmm', 'date': 'som
edate', 'time': 'sometime'}, {'id': '8888', 'name': 'nnnnn
n', 'date': 'somedate', 'time': 'sometime'}]