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

半城伤御伤魂 提交于 2019-12-13 14:25:01

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/53926562/compare-python-dictionary-values-of-type-list-to-see-if-they-match-in-that-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!