代码之家  ›  专栏  ›  技术社区  ›  GAP2002

如何从字典数组创建一组字典键

  •  0
  • GAP2002  · 技术社区  · 5 年前

    {
        "x": {
            "a": 1,
            "b": 2,
            "c": 3
        },
        "y": {
            "a": 1,
            "b": 2,
            "d": 4
        }
    }
    

    我想创建一个 set

    {"a", "b", "c", "d"}
    

    我花了很长时间在这个问题上,但总是以错误告终: TypeError: unhashable type: 'dict_keys' .

    我现在的代码是:

    set(item.keys() for item in [dictonary for dictonary in self.data.values()])
    

    理想情况下,我不想使用任何模块,但如果需要,我会。

    2 回复  |  直到 5 年前
        1
  •  2
  •   ShadowRanger    5 年前

    你可以做两个中的一个 微小的

    1. keys 对象(并删除无意义的no op inner listcomp):

      set().union(*[dictionary.keys() for dictionary in self.data.values()])
      # Or somewhat less obviously, but more efficiently, you can just union 
      # the dicts themselves, which already act as collections of their keys:
      set().union(*self.data.values())
      

      这将生成一个空集,然后将所有键视图(或 dict 作为与之结合的位置论据; set.union

    2. 在应用程序中正确使用嵌套循环 单一的 理解,而不是一种嵌套在另一种理解中的理解(这并不像你预期的那样解包):

      set(item for dictionary in self.data.values() for item in dictionary)
      # Or slightly better, but not as close to what you wrote, a true set comprehension
      {item for dictionary in self.data.values() for item in dictionary}
      

        2
  •  2
  •   Prune    5 年前

    您的直接问题是您试图将密钥列表添加到集合中。 这个 导致了 {['a', 'b', 'c'], ['a', 'b', 'd']} ,但不能将可变元素放入集合(不可更改)。

    相反,您需要遍历这些键并将它们分别放入集合中。

    [dictionary for dictionary in self.data.values()] 更好地表达为 list(self.data.values()) .

    src = {
        "x": {
            "a": 1,
            "b": 2,
            "c": 3
        },
        "y": {
            "a": 1,
            "b": 2,
            "d": 4
        }
    }
    
    result = set(key for item in src.values() for key in item.keys())
    print(result)