I have a text file with some values in it. My text file:
297147
339761
357586
94922
207611
572399
575970
304557
218365
286313
29984
11511
323460
516916
21711
313386
402639
457584
488377
301753
183319
397063
497660
235784
319073
I have another .json file that contains dictionaries. My json file:
{
"license":4,
"file_name":"COCO_val2014_000000522418.jpg",
"coco_url":"http://images.cocodataset.org/val2014/COCO_val2014_000000522418.jpg",
"height":480,
"width":640,
"date_captured":"2013-11-14 11:38:44",
"flickr_url":"http://farm1.staticflickr.com/1/127244861_ab0c0381e7_z.jpg",
"id":522418
},
{
"license":3,
"file_name":"COCO_val2014_000000184613.jpg",
"coco_url":"http://images.cocodataset.org/val2014/COCO_val2014_000000184613.jpg",
"height":336,
"width":500,
"date_captured":"2013-11-14 12:36:29",
"flickr_url":"http://farm3.staticflickr.com/2169/2118578392_1193aa04a0_z.jpg",
"id":184613
},
I want to retrive those dictionaries in json file whose "id"s match with the values in text file
I tried a code
#to retrive the json file key **"id"**
import json
with open("file.json") as f:
data_retreived= json.load(f)
a=data_retreived["images"]
for d in a:
print(d['id'])
#to retrieve the text_file values
q = open("/content/drive/MyDrive/coco/data.txt", "r")
li=q.readlines()
print(li)
Now I am trying something like this to retrieve the matching values
res=[]
for wt in li:
for f in a:
if wt == f['id']:
res.append(f)
print(res)
But it gives me output:
None
json.load(f)
automatically parses integers into int
s. While q.readlines()
doesn't and reads them as strings. So if wt == f['id']
compares a string with an integer which is always false. Try if int(wt) == f['id']
.