我将得到每个键的交集。我的字典是:
dict_1 = {101: [['14', '02', '03', '07', '11'], ['04', '12', '05', '06', '08'], ['10', '16', '09', '13', '01']],
102: [['21', '19', '14', '07', '10'], ['11', '04', '09', '12', '13'], ['03', '02', '15', '08', '17']]
}
dict_2 = {101: [['12', '02', '05', '01', '16'], ['04', '03', '18', '10', '14'], ['10', '11', '08', '07', '13']],
102: [['21', '19', '11', '07', '15'], ['08', '03', '09', '12', '13'], ['03', '02', '15', '10', '17']]
}
我所说的交集(对于101)是指:
list_1 = Common elements in ['14', '02', '03', '07', '11'] and ['12', '02', '05', '01', '16']
list_2 = Common elements in ['14', '02', '03', '07', '11'] and ['04', '03', '18', '10', '14']
list_3 = Common elements in ['14', '02', '03', '07', '11'] and ['10', '11', '08', '07', '13']
list_4 = Common elements in ['04', '12', '05', '06', '08'] and ['12', '02', '05', '01', '16']
list_5 = Common elements in ['04', '12', '05', '06', '08'] and ['04', '03', '18', '10', '14']
list_6 = Common elements in ['04', '12', '05', '06', '08'] and ['10', '11', '08', '07', '13']
list_7 = Common elements in ['10', '16', '09', '13', '01'] and ['12', '02', '05', '01', '16']
list_8 = Common elements in ['10', '16', '09', '13', '01'] and ['04', '03', '18', '10', '14']
list_9 = Common elements in ['10', '16', '09', '13', '01'] and ['10', '11', '08', '07', '13']
最终输出应如下所示:
output = {101: [['02'], ['14', '03'], ['07', '11'], ['12', '05'], ['04'], ['08'], ['16', '01'], ['10'], ['10', '13']],
102: [['21', '19', '07'], [], ['10'], ['11'], ['09', '12', '13'], [], ['15'], ['03', '08'], ['03', '02', '15', '17']]
}
什么是最好的方法呢?
我可以得到两个列表的所有公共元素,但是我不能在嵌套字典中这样做。
1条答案
按热度按时间owfi6suc1#
您可以执行以下操作:
基本上你可以迭代
dict_1
的值,它本身就是一个列表,对于每个子列表,你可以迭代dict_2
的值的子列表,使用intersection
你可以得到公共项。如果你愿意,这可以写成字典理解。下面是完整的代码:
['14', '03']
这样的公共键的顺序。如果这对你来说也很重要,你应该使用另一个嵌套循环来检查成员测试: