Consolidate dictionary based on repeat values
I have a dictionary set up like this
{
"key1" : [1,2,4],
"key2" : [2,4],
"key3" : [1,2,4],
开发者_JAVA技巧 "key4" : [2,4],
....
}
What I want is something like this.
[
[
["key1", "key3"],
[1,2,4],
],
[
["key2", "key4"],
[2,4],
],
.....
]
A list of keys and values based on unique value pairs. How can I do this in a pythonic way?
You can invert the dictionnary like this :
orig = {
"key1" : [1,2,4],
"key2" : [2,4],
"key3" : [1,2,4],
"key4" : [2,4],
}
new_dict = {}
for k, v in orig.iteritems():
new_dict.setdefault(tuple(v), []).append(k) #need to "freeze" the mutable type into an immutable to allow it to become a dictionnary key (hashable object)
# Here we have new_dict like this :
#new_dict = {
# (2, 4): ['key2', 'key4'],
# (1, 2, 4): ['key3', 'key1']
#}
# like sverre suggested :
final_output = [[k,v] for k,v in new_dict.iteritems()]
Here is a list comprehension to do the job cleanly:
[[[key for key in dictionary.keys() if dictionary[key] == value], value]
for value in unique(list(dictionary.values()))]
Where unique
can be a function that returns the unique elements of a list. There is no default for this, but there are many implementations (here are some).
Please find my sample code below if it is still actual for you:
orig = {
"key1" : [1,2,4],
"key2" : [2,4],
"key3" : [1,2,4],
"key4" : [2,4],
}
unique = map(list, set(map(tuple, orig.values())))
print map(lambda val: [val, filter(lambda key: orig[key] == val, orig)], unique)
精彩评论