简体   繁体   中英

compare python dictionary values of type list to see if they match in that order

prefs = 
{
    's1': ["a", "b", "c", "d", "e"],
    's2': ["c", "d", "e", "a", "b"],
    's3': ["a", "b", "c", "d", "e"],
    's4': ["c", "d", "e", "b", "e"]
}

I have a dictionary, and I want to compare the values (Type: List) for each key to see if they exist in that order. So essentially I'm trying to iterate over each key-value pair and compare the value which is of type list to the next value to see if the elements in that list match in that specific order. If we find a match, I want to return a list of keys that make the match.

ex: s1 value is a list with elements "a", "b", "c", "d", "e", so I want to check other values with the elements in the same order. So in this case key s3 would be returned since the values match with the same exact order. s1 value = s3 value because of the elements in the list match in the same order. return list would be something like [s1:s3], and multiple matches should be returned.

To find matching lists, you could do something like this:

prefs = {
    's1': ["a", "b", "c", "d", "e"],
    's2': ["c", "d", "e", "a", "b"],
    's3': ["a", "b", "c", "d", "e"],
    's4': ["c", "d", "e", "b", "e"],
    's5': ["c", "d", "e", "b", "e"]
}

matches = {}
for key, value in prefs.items():
    value = tuple(value)
    if value not in matches:
        matches[value] = []
    matches[value].append(key)

print(matches)

Which prints:

{('a', 'b', 'c', 'd', 'e'): ['s1', 's3'], ('c', 'd', 'e', 'b', 'e'): ['s5', 's4'], ('c', 'd', 'e', 'a', 'b'): ['s2']}

(Note: I added s5 to prefs .)


Update

If you just want the grouped keys, you can access them via matches.values() :

print(*matches.values())

Which prints:

['s4', 's5'] ['s1', 's3'] ['s2']

Also, you can do the whole thing in one line if you want:

print({value: [key for key in prefs if tuple(prefs[key]) == value] for value in set(map(tuple, prefs.values()))})

First sort by values using sorted then use itertools.groupby

prefs = {
            's1': ["a", "b", "c", "d", "e"],
            's2': ["c", "d", "e", "a", "b"],
            's3': ["a", "b", "c", "d", "e"],
            's4': ["c", "d", "e", "b", "e"],
            's5': ["c", "d", "e", "a", "b"]
        }

from itertools import groupby
[[t[0] for t in g] for k,g in groupby(sorted(prefs.items(), key=lambda x:x[1]), lambda x:x[1])]
#[['s1', 's3'], ['s2', 's5'], ['s4']]

To print with values:

{tuple(k):[t[0] for t in g] for k,g in groupby(sorted(prefs.items(), key=lambda x:x[1]), lambda x:x[1])}

Output:

{('a', 'b', 'c', 'd', 'e'): ['s1', 's3'],
 ('c', 'd', 'e', 'a', 'b'): ['s2', 's5'],
 ('c', 'd', 'e', 'b', 'e'): ['s4']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM