python - 比较 JSON 文件中的多个字典?
问题描述
现在我有一个如下所示的 JSON 文件:
"suggested":[{
"city": "Berlin",
"location": "Europe",
"hotels": true,
"restaurants": true,
"rivers": false},
{
"city": "Andorra",
"location": "Global",
"hotels": false,
"restaurants": true,
"rivers": true
}]
我想将分割在字典中的那个 JSON 文件与这个“参考”JSON 文件进行比较:
"master":[{
"city": "",
"location": "Europe",
"hotels": true,
"restaurants": false,
"rivers": false
}]
我的目标是将 JSON 中键的值与 JSON 文件"master"
中的内部字典的值进行比较"suggested"
,并返回它们有多少匹配项的打印。例如:
"Berlin" matches with "Master" in (3) fields.
现在我用一个简单的函数在 python 中打开了我的 JSON 文件:
def openJsonFile(file):
with open (file) as json_data:
workData = json.load(json_data)
return(workData)
这个函数循环打开的文件:
def compareJsonFiles(suggested, master):
matches = 0
for key in suggested.keys():
value = suggested[key]
if key not in master:
print ("{0} doesn't have value in {1}".format(key, master))
else:
if master[key] == value:
print("for key %s values match" % key)
matches + 1
print(matches)
但是当我尝试通过字典时,我得到了这个错误:
AttributeError: 'list' object has no attribute 'keys'
更新: 我制作了这个函数,试图将 json 列表中的每个值作为单独的字典传递。
def jsonToDict(file):
for lsdt in file:
newListDic = file[lsdt]
for key in newListDic.keys():
value = newListDic[key]
print(value)
它可以给我一个听写。但它提示:
TypeError: list indices must be integers or slices, not dict
如何遍历 JSON 文件中的多个字典并将键值与另一个 JSON 文件进行比较?
PS:我已经搜索了将近两天没有成功,所以如果帖子发生的第一件事不是“标记为重复标志”,我会很高兴。
解决方案
您master
的节点是列表,而不是字典。如果您确定 master 始终只保存一个条目,请通过
compareJsonFiles(suggested_data, master_data[0])
推荐阅读
- python - 附加数组的numpy数组
- java - 我的代码运行顺序有问题
- animation - Flutter TextField 自动对焦不适用于 SlideTransition
- c++ - C++ / SDL2 - 球一起弹跳/故障
- flutter - 比较两个列表中的元素并在 Dart 中创建一个新列表
- python - 有没有办法通过重新格式化来汇总数据?
- python - 函数 np.std() 中的轴 (0, 1) 是什么意思?
- python - 将特定数字(无排序)移动到列表左侧
- java - 如何将类型(通用)传递给注释?
- if-statement - 我正在尝试使用重复和 if 条件将列中的单元格值减少 1