【问题标题】:Compare values from a dictionary of dictionary python比较字典python字典中的值
【发布时间】:2014-03-13 16:34:13
【问题描述】:

我有这个嵌套字典,我想检查值是否匹配以及它们是否不返回值。

dict_test = {'sct2': {(5, 5, 0): [1, 2, 3]}, 'sct1': {(5, 5, 0): [1, 2, 4]}}

所以基本上通过 dict_test 迭代,我将比较 'sct2' 和 'sct1' 字典中的值并查看它们是否匹配,如果它们不匹配,我将打印出不匹配的值。如果我分成 2 个字典然后比较它们,我可以做到这一点

test1=dict_test['sct2']
test2=dict_test['sct1']

我可以比较这两个字典并做这样的事情:

mismatch = [val for val in test1.itervalues() if not val in test2.itervalues()]

虽然我希望它返回 4 而不是列表,但它会返回 [1,2,4]

我想知道是否有更好的方法来做到这一点,而不必创建 2 个字典,感谢任何帮助。谢谢

【问题讨论】:

  • 所以你想比较[1,2,3][1,2,4]
  • 您只想比较具有相同元组键的条目吗?
  • 您的示例似乎没有使用 test2,但确实使用了未定义的 y;听起来不对……
  • 对不起,应该是test2而不是y,已经改了。

标签: python dictionary nested


【解决方案1】:

如果没有更好地了解您要解决的问题,这里的代码将根据您的test_dict 返回((3,4))。如果您想要更好地解决您的问题的答案,请更清楚地说明您的问题、限制和要求。

def diffList(a,b):
    '''Assumption: a and b are same length
    Returns non-matching ordered pairs of a and b
    '''
    return filter(lambda ai, bi: ai != bi, zip(a,b)))

outerKeyPairs = [(outerKeyA, outerKeyB) for outerKeyA in test_dict for outerKeyB in test_dict if outerKeyA > outerKeyB]
for outerKeyA, outerKeyB in outerKeyPairs:
    for innerKey in test_dict[outerKeyA]:
        if innerKey in test_dict[outerKeyB]:
            yield diffList(test_dict[outerKeyA][innerKey], test_dict[outerKeyB][innerKey])

【讨论】:

    【解决方案2】:

    使用minus operator of sets,它给出了两组的差异。为清楚起见,您可以改用差异方法,这也会产生差异。

    mismatch = list(filter(set(s2)-set(s1) for s1 in dict_test["sct2"].values()\
                for s2 in dict_test["sct1"].values()))
    

    【讨论】:

    • 减号运算符需要显式转换为集合。
    • @IceArdor 真;我认为减号运算符和差分方法是相同的。但是,差异方法隐式地将s1 转换为集合,而减号运算符则不会。将提交有关此问题的错误报告(或增强请求)。
    • 这里没有必要将s2 中的键转换为集合...使用s2.viewkeys() - s1 来利用其- 工作的dict 视图对象任意迭代。
    • 我也不会费心提出增强请求 - set 的函数的操作符版本被故意设计为不接受非集合兼容类型的迭代。
    • @JonClements 参考它是故意设计的?关于另一条评论,s2 不是字典,而是列表。去睡觉了。
    【解决方案3】:

    一个相当干净的方法是:

    def diff_list(l1, l2):
        s = set(l2)
        return [i for i in l1 if i not in s]
    
    {t:diff_list(l1, test2[t]) for (t,l1) in test1.iteritems()}
    

    这会生成每个不同键与缺失值列表的映射:

    {(5, 5, 0): [3]}
    

    请注意,上面diff_list 的逻辑假设您不关心每个列表中项目的位置和数量。如果这很重要,diff_list 可以实现为:

    def diff_list(l1, l2):
        return {i: (v[0], v[1]) for i,v in enumerate(map(None, l1, l2)) if v[0] != v[1]}
    

    使用这种方法,您会得到以下输出:

    >>> test1  # Here's what test1 looks like
    {(5, 5, 0): [1, 2, 3]}
    
    >>> test2  # Here's what test2 looks like
    {(5, 5, 0): [1, 2, 4]}
    
    >>> {t:diff_list(l1, test2[t]) for (t,l1) in test1.iteritems()} # Getting the difference
    {(5, 5, 0): {2: (3, 4)}}
    

    也就是说,您会得到一个字典,其中包含 test1test2 中的每个不同键,映射到包含每个不同索引的字典,以及两个不同列表中该索引处的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多