Python-获取两个Json文件的交集 [英] Python - Getting the intersection of two Json-Files
问题描述
我正在寻找一个选项来计算两个JSON文件的交集.我一直在寻找它,发现我可以使用集解决我的问题.这个工作好".但是我必须对交叉路口有更详细的了解.这就是问题的开始.
i'm looking for an option to calculate the intersection of two JSON-Files. I have been searching for it and found that i can use sets for my problem. This works "okay". But i have to get a more detailed view of the intersection. And this is where the problems are starting.
我如何计算交集:
def calcIntersect(ValidationFile, json_object1, json_object2):
with open(ValidationFile) as schema_file:
schema = j.load(schema_file)
js.Draft4Validator.check_schema(schema)
with open(json_object1) as spec_file:
spec1 = j.load(spec_file, object_pairs_hook=OrderedDict)
js.validate(spec1, schema)
with open(json_object2) as spec_file:
spec2 = j.load(spec_file, object_pairs_hook=OrderedDict)
js.validate(spec2, schema)
x = set(spec1) & set(spec2)
print(x)
示例数据1:
{
"Car":{
"Brand":"Audi",
"Nationality":"Germany",
"Modelname":"A6"
},
"Engine":{
"cubic capacity":"2967",
"Enginetype":"V6",
"Fuel":"Diesel",
"MaxSpeed":"250"
},
"Colors":{
"Carcolor":"Black",
"Interiorrcolor":"white"
}
}
示例数据2:
{
"Car":{
"Brand":"Audi",
"Nationality":"USA",
"Modelname":"A6"
},
"Engine":{
"cubic capacity":"2995",
"Enginetype":"V6",
"Fuel":"Petrol",
"MaxSpeed":"250"
},
"Colors":{
"Carcolor":"Black",
"Interiorrcolor":"Black"
}
}
示例输出:
{'Car', 'Colors', 'Engine'}
这只是键",但我需要字典.目前,它给我这个键是要说其中有一个交叉点.也许在汽车"中,两个文件中都有一个奥迪",并且国籍也有所不同,因为一辆汽车是在美国生产的,而另一辆汽车是在德国生产的.但是它仍然返回"Car"而不是"Audi".
This are just the "Keys" but i need the dictonaries. At the moment it is giving me this keys to say that there is a intersection in it. Maybe in 'Car' there is in both Files a "Audi" and the nationality is different because one car is produced in America and the other car is produced in Germany. But still it returns 'Car' and not the "Audi".
我希望我能描述一下我的问题.这是我的第一个问题.
I hope i were able to describe my problem for a bit. It's my first question..
推荐答案
受@likeon的回答启发,以下几行代码将为您提供一本字典,其键将成为您规格中相交对象的键,其值包含相交对象的数组.
The following lines, inspired by @likeon's answer, will give you a dictionary whose keys will be the keys of the intersecting objects in your specs, and the values an array containing the intersecting objects.
intersect = { key: [o, spec2[key]] for key, o in spec1.iteritems()
if key in spec2 };
修改:
如果您使用的是 python 3 ,则必须使用items
而不是iteritems
:
Edit:
If you are using python 3, you must use items
instead of iteritems
:
intersect = { key: [o, spec2[key]] for key, o in spec1.items()
if key in spec2 };
这篇关于Python-获取两个Json文件的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!