Python 如何选择具有特定值的特定JSON对象?
我在里面有多个字典的列表(如JSON),我有一个值列表,基于这个值,我希望JSON对象代表那个特定的值。例如Python 如何选择具有特定值的特定JSON对象?,python,json,Python,Json,我在里面有多个字典的列表(如JSON),我有一个值列表,基于这个值,我希望JSON对象代表那个特定的值。例如 [{'content_type': 'Press Release', 'content_id': '1', 'Author':John}, {'content_type': 'editorial', 'content_id': '2', 'Author': Harry }, {'content_type': 'Article', 'content_id': '3'
[{'content_type': 'Press Release',
'content_id': '1',
'Author':John},
{'content_type': 'editorial',
'content_id': '2',
'Author': Harry
},
{'content_type': 'Article',
'content_id': '3',
'Author':Paul}]
我想在作者是Paul的地方获取完整的对象。
这是我到目前为止所做的代码
import json
newJson = "testJsonNewInput.json"
ListForNewJson = []
def testComparision(newJson,oldJson):
with open(newJson, mode = 'r') as fp_n:
json_data_new = json.load(fp_n)
for jData_new in json_data_new:
ListForNewJson.append(jData_new['author'])
如果需要任何其他信息,请询问。案例1
一次性访问 完全可以读取数据并对其进行迭代,返回找到的第一个匹配项
def access(f, author):
with open(file) as f:
data = json.load(f)
for d in data:
if d['Author'] == author:
return d
else:
return 'Not Found'
案例2
重复访问 在这种情况下,明智的做法是以这样一种方式重塑数据,即通过作者姓名访问对象要快得多(想想字典吧!) 例如,一种可能的选择是:
with open(file) as f:
data = json.load(f)
newData = {}
for d in data:
newData[d['Author']] = d
现在,定义一个函数并传递预加载的数据以及作者姓名列表
def access(myData, author_list):
for a in author_list:
yield myData.get(a)
函数的调用方式如下:
for i in access(newData, ['Paul', 'John', ...]):
print(i)
或者,将结果存储在列表r
中。列表(…)
是必需的,因为yield
返回一个生成器对象,您必须通过迭代来耗尽它
r = list(access(newData, [...]))
为什么不这样做呢?它应该是快速的,你将不必加载不会被搜索的作者
alreadyknown = {}
list_of_obj = [{'content_type': 'Press Release',
'content_id': '1',
'Author':'John'},
{'content_type': 'editorial',
'content_id': '2',
'Author': 'Harry'
},
{'content_type': 'Article',
'content_id': '3',
'Author':'Paul'}]
def func(author):
if author not in alreadyknown:
obj = get_obj(author)
alreadyknown[author] = obj
return alreadyknown[author]
def get_obj(auth):
return [obj for obj in list_of_obj if obj['Author'] is auth]
print(func('Paul'))
您将不止一次执行此类搜索吗?是的。我可能想找到多个作者,循环会让它变得有点慢。可能是@LaxmikantGurnalkar的重复,但OP的问题还有其他隐藏的细微差别,我觉得我的答案更好地解决了这个问题(目标不会)。