【问题标题】:How to retrieve dictionary that matches the value in another text file如何检索与另一个文本文件中的值匹配的字典
【发布时间】:2021-10-15 18:32:37
【问题描述】:

我有一个包含一些值的文本文件。 我的文本文件:

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

我有另一个包含字典的 .json 文件。 我的 json 文件:

{
   "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
},

我想检索 json 文件中“id”text 文件中的值匹配的那些字典

我尝试了一个代码

#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)

现在我正在尝试这样的方法来检索匹配值

res=[]
for wt in li:
  for f in a:
    if wt == f['id']:
      res.append(f)
print(res)

但它给了我输出:

【问题讨论】:

  • PLEASE DO NOT POST TEXT AS IMAGES。将文本复制并粘贴到您的问题中,并使用代码格式化工具正确格式化。图像不可搜索,也无法通过屏幕阅读器为有视力障碍的人解读。使用edit 链接修改您的问题。
  • @MattDMo 我刚刚编辑过

标签: python dictionary key match key-value


【解决方案1】:

json.load(f) 自动将整数解析为ints。而q.readlines() 没有并将它们作为字符串读取。因此if wt == f['id'] 将字符串与始终为假的整数进行比较。试试if int(wt) == f['id']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2013-08-29
    • 2021-09-30
    相关资源
    最近更新 更多