簡體   English   中英

返回具有相同列表值的字典鍵

[英]return dictionary keys with the same list values

我有一本這樣的字典:

example_dict = {'list_1': [1, 2, 'x'], 'list_2':[1, 3, 'x'], 'list_3' : [1, 2, 'x'], 'list_4': [1, 2, 'd'], 'list_5': [1, 3, 'x'] }

並且需要在不知道這些值的情況下返回具有相同值(列表)的鍵的列表(或其他形式)。 結果應如下所示:

[['list_1', 'list_3'], ['list_2','list_5']]

您可以將值轉換為元組並將它們用作臨時字典中的鍵:

嘗試:

example_dict = {
    "list_1": [1, 2, "x"],
    "list_2": [1, 3, "x"],
    "list_3": [1, 2, "x"],
    "list_4": [1, 2, "d"],
    "list_5": [1, 3, "x"],
}

out = {}
for k, v in example_dict.items():
    out.setdefault(tuple(v), []).append(k)

print(list(v for v in out.values() if len(v) > 1))

印刷:

[['list_1', 'list_3'], ['list_2', 'list_5']]
example_dict = {'list_1': [1, 2, 'x'], 'list_2':[1, 3, 'x'], 'list_3' : [1, 2, 'x'], 'list_4': [1, 2, 'd'], 'list_5': [1, 3, 'x'] }

keys = []
for k, v in example_dict.items():
    l = []
    if list(example_dict.values()).count(v) > 1:
        for k_, v_ in example_dict.items():
            if v == v_ and k_ not in l:
                l.append(k_)
    if l not in keys and len(l) > 1:
        keys.append(l)

我確信存在像上面這樣更好更短的方法。 但是對於像我們這樣的初學者來說可能會更容易理解:)

暫無
暫無

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

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