在JSON格式的字典中检查值

2024-09-29 21:31:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查给定的字符串(“Sample1”)是否在这个字典的“text”字段中。我做错什么了?你知道吗

var = {'data': [{'text': 'Sample1',
                  'descriptionMoreURL': 'https://sample1.com',
                  'description': 'this is sample1',
                  'type': 'text'},
                 {'text': 'Sample2',
                  'descriptionMoreURL': 'https://sample2.com',
                  'description': 'this is sample2',
                  'type': 'text'}
                 ]}

print('Sample1' in var['data'])

例如,在这段代码中,我希望输出为True。类似地,如果字符串“Sample1”被替换为“Sample2”,它也将返回True。你知道吗


Tags: 字符串texthttpscomdataisvartype
2条回答

print('Sample1'在var['data'])按dict[{},{},{}]的顺序检查字符串

尝试一些:

for el in var['data']:
   print('Sample1' in el.values())

你的检查比需要的高一级。'Sample1'var['data']中不作为键存在,但在较低的嵌套字典中确实存在。你知道吗

您可以在这里使用^{}来检查每个字典中是否存在'Sample1'值:

>>> any(d['text'] == 'Sample1' for d in var['data'] for k in d)
True
>> any(d['text'] == 'Sample2' for d in var['data'] for k in d)
True

相关问题 更多 >

    热门问题