在Python中使用相同的键在字典中查找不同的值

时间:2018-06-26 05:47:54

标签: python python-3.x dictionary

我有2个字典列表,它们具有相同的键,但值不同。

function changeLanguage(lang){
$.post("/misc/sessionUpdate.asp",{ 'lang': lang}); 
$.getJSON("/language/"+lang+".json", function( data ) {

    $.each(data, function(property, val){

        $('[data-localize]').val(function() {
            type =  $(this).attr("type");
            attrVal = $(this).attr("data-localize");
                    // if put return data[property]; here it is working but the problem it should be inside the if(attrVal == property)
            if(attrVal == property){
                if (type == "submit"){
                    // i already tried console.log (attrVal +"=="+ property) to verify if there is an instance of true and there is
                    return data[property];
                }else{
                    attrName = '[data-localize="'+property+'"]'; //sample format [data-localize=menu]
                    $(attrName).html(val); // data[property] is the corresponding value of the key in json
                }
            }               
        });
    });
}).done(function(){
    $('.languageLoader').css('display','none');
});
}

我想得到2个字典列表;

一个是Dict_one中的值的字典列表,但不是Dict_two中的值。

另一个是Dict_two中的值的字典列表,但Dict_one中没有。

结果示例:

Dict_one = {"A": ["a1", "a2", "a3"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c4"]}

Dict_two = {"A": ["a1"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c5"]}

获取输出的最pythonic方法是什么?

编辑:它们始终具有相同的键。

7 个答案:

答案 0 :(得分:2)

您可以在字典理解中使用set.difference

In [29]: Result_one_two = {k: set(Dict_one[k]).difference(Dict_two[k]) for k in Dict_one}

In [30]: Result_one_two
Out[30]: {'A': {'a2', 'a3'}, 'B': set(), 'C': {'c4'}}

In [31]: Result_two_one = {k: set(Dict_two[k]).difference(Dict_one[k]) for k in Dict_one}

In [32]: Result_two_one
Out[32]: {'A': set(), 'B': set(), 'C': {'c5'}}

最好首先将值保留为set。在这种情况下,您无需为每个值调用集合。还要注意,如果您使用的是Python-3.6 +,因为这些版本中的字典是按插入顺序排序的,则输出将如预期的那样,否则应使用OrderedDict来跟踪订单。但是,如果此处的性能不是问题,并且/或者您正在处理的数据集较短,则可以使用列表理解,如其他答案所述。

此外,如注释中所述,如果值顺序对于您很重要,以便利用集合操作并保持顺序,则可以使用自定义有序集合,如Raymond在此处https://stackoverflow.com/a/10006674/2867928所建议的那样Hettinger。

答案 1 :(得分:1)

您可以这样做:

Result_one_two = {
    k: [v for v in vals if v not in Dict_two.get(k, [])]
    for k, vals in Dict_one.items()
}

输出:

Result_one_two = {'A': ['a2', 'a3'], 'C': ['c4'], 'B': []}

第二个:

Result_two_one = {
    k: [v for v in vals if v not in Dict_one.get(k, [])]
    for k, vals in Dict_two.items()
}

输出:

Result_two_one = {'A': [], 'C': ['c5'], 'B': []}

答案 2 :(得分:1)

我希望这段代码对您有帮助

#first one:
dict_one = {"a":["a1","a2","a3"], "b": ["b1","b2"], "c":["c1","c2","c3","c4"]}
dict_two = {"a": ["a1"], "b":["b1","b2"], "c": ["c1","c2","c3","c5"]}
dict_end = {}
dict_end2 = {}
for i in dict_one:
  for j in (dict_one[i]):
    if j not in dict_two[i]:
      dict_end[i] = j

print (dict_end)
#second one goes below : 
for i in dict_two:
  for j in (dict_two[i]):
    if j not in dict_one[i]:
      dict_end2[i] = j

print (dict_end2)

答案 3 :(得分:0)

Dict_one = {"A": ["a1", "a2", "a3"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c4"]}
Dict_two = {"A": ["a1"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c5"]}

dict(map(lambda k: (k, list(set(Dict_one[k]) - set(Dict_two.get(k, [])))), Dict_one))
# {'A': ['a2', 'a3'], 'B': [], 'C': ['c4']}

dict(map(lambda k: (k, list(set(Dict_two.get(k, [])) - set(Dict_one[k]))), Dict_one))
# {'A': [], 'B': [], 'C': ['c5']}

答案 4 :(得分:0)

类似于@kasramvd

Dict_one = {"A": ["a1", "a2", "a3"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c4"]}
Dict_two = {"A": ["a1"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c5"]}

Result_one_two = {key:list(set(Dict_one[key])-set(Dict_two[key])) for key in Dict_one.keys()}
Result_two_one = {key:list(set(Dict_two[key])-set(Dict_one[key])) for key in Dict_two.keys()}

答案 5 :(得分:0)

不使用字典理解

for x,y in zip(Dict_one,Dict_two):
    g=set(Dict_one[x])
    h=set(Dict_two[x])
    Result_one_two[x]=[list(g.difference(h))]
    Result_two_one[x]=[list(h.difference(g))]

答案 6 :(得分:0)

您可以尝试几种dict理解:

Dict_one = {"A": ["a1", "a2", "a3"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c4"]}

Dict_two = {"A": ["a1"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c5"]}

# Remove this line and just loop over DictOne if using Python 3.6+
sort_keys = sorted(Dict_one)

Result_one_two = {k: [x for x in Dict_one[k] if x not in Dict_two[k]] for k in sort_keys}
Result_two_one = {k: [x for x in Dict_two[k] if x not in Dict_one[k]] for k in sort_keys}

print(Result_one_two)
print(Result_two_one)

哪些输出:

{'A': ['a2', 'a3'], 'B': [], 'C': ['c4']}
{'A': [], 'B': [], 'C': ['c5']}

注意::如果您未使用Python 3.6+,则由于不能保证顺序,因此必须按排序顺序或使用collections.OrderedDict()遍历键。否则,您可以正常循环浏览键并保留顺序。

这还假设Dict_oneDict_two具有相同的键。