Home > OS >  return dictionary keys with the same list values
return dictionary keys with the same list values

Time:07-30

I have a dictionary like this:

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'] }

and need to return lists (or some other form) of keys that have the same values (lists) without knowing these values. The result should look something like this:

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

CodePudding user response:

You can convert values to tuples and use them as a key in temporary dictionary:

Try:

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))

Prints:

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

CodePudding user response:

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)

I am sure that better and shorter way like above exists. But probably it would be more understandable for beginners like us :)

  • Related