簡體   English   中英

我需要一個帶有兩個鍵的類似字典的結構,您可以在其中獲取所有對象的列表,其中一個具有特定值

[英]I need a dict-like structure with two keys, where you can get the list of all objects with a certain value of one of them

假設我有一個看起來像這樣的字典:

d['a']['1'] = 'foo'
d['a']['2'] = 'bar'
d['b']['1'] = 'baz'
d['b']['2'] = 'boo'

如果我想得到第一個鍵是'a'的每一個項目,我可以做d['a']我會得到所有的。 但是,如果我想獲取第二個鍵為“1”的所有項目怎么辦? 我能想到的唯一方法是制作第二個字典,鍵的順序相反,這需要復制內容。 有沒有辦法在一個單一的結構中做到這一點?

編輯:忘了提:我想在不迭代所有內容的情況下做到這一點。 我將要處理具有數十萬個鍵的字典,所以我需要一些可擴展的東西。

在此示例中,您正在處理三個字典:一個具有值“foo”和“bar”,一個具有值“baz”和“boo”,以及一個映射鍵“a”和“b”的外部字典到前兩個內部詞典。 您可以使用嵌套的 for 循環遍歷外部和內部字典的鍵:

items = []
for outer_key in d:
    for inner_key in d[outer_key]:
        if inner_key == "1":
            items.append(d[outer_key][inner_key])
            break  # No need to keep checking keys once you've found a match

如果您不關心外部字典的鍵,您也可以使用d.values()忽略鍵並只查看內部字典,然后對這些進行直接成員資格檢查:

items = []
for inner_dict in d.values():
    if "1" in inner_dict:
        items.append(inner_dict["1"])

這也可以寫成列表推導:

items = [inner_dict["1"] for inner_dict in d.values() if "1" in inner_dict]

你想要的聽起來非常類似於可以作為字典字典實現的樹結構。 這是一個簡單的實現,取自問題的答案之一實現嵌套字典的最佳方法是什么?

class Tree(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

    def get_second_level(self, second_key):
        found = []
        for level2 in self.values():
            if second_key in level2:
                found.append(level2[second_key])
        return found

d = Tree()
d['a']['1'] = 'foo'
d['a']['2'] = 'bar'
d['b']['1'] = 'baz'
d['b']['2'] = 'boo'
d['c']['2'] = 'mox'
d['c']['3'] = 'nix'

print(d)            # -> {'a': {'1': 'foo', '2': 'bar'}, 'b': {'1': 'baz', '2': 'boo'},
                    #     'c': {'2': 'mox', '3': 'nix'}}
print(d['a'])       # -> {'1': 'foo', '2': 'bar'}
print(d['a']['1'])  # -> foo
print(d['a']['2'])  # -> bar

print()
second_key = '1'
found = d.get_second_level(second_key)
print(f'Those with a second key of {second_key!r}')  # -> Those with a second key of '1'
print(f'  {found}')                                  # ->   ['foo', 'baz']

因此,在睡了之后,我想出的解決方案是制作三個字典,其中數據實際存儲並由元組( d['a', '1'] = 'foo' )標識的主要字典和另一個兩個是在鍵 A 下存儲鍵 B 的所有可能值的索引,其中 (A,B) 是有效組合(因此a['a'] = ['1', '2'] , b['1'] = ['a', 'b'] . 我不完全喜歡這個,因為它仍然需要大量的存儲開銷並且不能有效地擴展到更多的鍵,但是它可以在不迭代和不復制的情況下完成工作數據。如果有人有更好的主意,我會很高興聽到。

暫無
暫無

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

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