簡體   English   中英

如何從字典數組創建一組字典鍵

[英]How to create a set of dictionary keys from an array of dictionaries

我有一個這樣的字典:

{
    "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()])

理想情況下,我不想使用任何模塊,但如果需要我會。

您的直接問題是您試圖將鍵列表添加到您的集合中。 導致集合{['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)

您可以進行兩項微小更改之一,以使您編寫的內容生效:

  1. 聯合keys對象(並刪除無意義的無操作內部列表組合):

     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本身)解包為位置 arguments 以與之結合; set.union接受可變參數,因此您可以將任意數量的 collections 傳遞給它,以便立即聯合在一起。

  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}

    注意循環的東西的順序是不同的; 在這種多循環理解中,最左邊的循環是外循環,當您向右 go 時移動到內循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM