我有一个字典列表如下:
[{'EchoTime': 0,
'FlipAngle': 90,
'MRAcquisitionType': '2D',
'MagneticFieldStrength': 3,
'Manufacturer': 'SIEMENS',
'ManufacturerModelName': 'TrioTim',
'RepetitionTime': 2,
'ScanOptions': 'FS',
'ScanningSequence': 'EP',
'SequenceName': 'epfid2d1_64',
'SequenceVariant': 'SK',
'SliceTiming': [[0.0025000000000000022],
[0.5],
[-0.030000000000000027],
[0.46625],
[0.168749999995],
[-0.36124999999999996],
[-0.46124999999500005],
[0.036250000005000005]],
'TaskName': 'tom'},
{'EchoTime': 0,
'FlipAngle': 90,
'MRAcquisitionType': '2D',
'MagneticFieldStrength': 3,
'Manufacturer': 'SIEMENS',
'ScanningSequence': 'EP',
'SequenceName': 'epfid2d1_64',
'SequenceVariant': 'SK',
'SliceTiming': [[0.0037500000050000315],
[0.5],
[-0.030000000000000027],
[0.46750000001500003],
[-0.0625],
[0.36750000001],
[-0.16249999998999998],
[0.33500000000499996],
[-0.19499999998999995],
[0.301250000005]],
'TaskName': 'tom'},
{'EchoTime': 0,
'FlipAngle': 90,
'MRAcquisitionType': '2D',
'MagneticFieldStrength': 3,
'RepetitionTime': 2,
'ScanOptions': 'FS',
'ScanningSequence': 'EP',
'SequenceName': 'epfid2d1_64',
'SequenceVariant': 'SK',
'SliceTiming': [[0.0025000000000000022],
[0.5],
[-0.030000000000000027],
[0.46625],
[-0.19625000000000004],
[0.301250000005],
[-0.22875],
[0.26749999999999996],
[-0.26249999999500007]],
'TaskName': 't1'},
{'EchoTime': 0,
'FlipAngle': 90,
'MRAcquisitionType': '2D',
'Manufacturer': 'SIEMENS',
'ManufacturerModelName': 'TrioTim',
'SequenceVariant': 'SK',
'SliceTiming': [[0.0025000000000000022],
[0.5],
[-0.030000000000000027],
[0.46625],
[-0.06374999999999997],
[0.43375000000499997],
[-0.09624999999999995],
[0.4],
[-0.22875],
[0.26749999999999996],
[-0.26249999999500007],
[0.235]],
'TaskName': 'fb'}]
列表中有大约2000个字典。 现在我想在列表中的所有字典中找到公共密钥:值对。 对于我使用以下功能:
def twodict_intersec(json1, json2):
d = {x:json1[x] for x in json1 if x in json2}
return d
for i in range(0,10,1):
print(i)
if i == 0:
res = twodict_intersec(json_list[i], json_list[i+1])
else:
res = dict_intersect(res, json_list[i+1])
print(res)
但输出如下所示,其中每个键包含所有值的列表而不是公共值
res = {'EchoTime': [[[[[[[[[0, 0], 0], 0], 0], 0], 0], 0], 0], 0], 'FlipAngle': [[[[[[[[[90, 90], 90], 90], 90], 90], 90], 90], 90], 90], 'ManufacturerModelName': [[[[[[[[['TrioTim', 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim'], 'TrioTim']}
我无法获得输出,其中每个键只有一个值在所有dict中都是常见的而不是上述情况。有人可以指出我的错误吗?
答案 0 :(得分:2)
您可以通过以下方式比较词典列表中的所有元素:
import copy
li = [{
"keep this value":5,
"remove this":59
},{
"keep this value":5,
"remove this":12
}]
def compareList(li):
result = copy.deepcopy(li[0])
for element in li:
for key in element:
if key in result and result[key] != element[key]:
del result[key]
return result
print (compareList(li))