2011-05-31 93 views
2

我有一本字典設立這樣整合基於重複字典值

{ 
    "key1" : [1,2,4], 
    "key2" : [2,4], 
    "key3" : [1,2,4], 
    "key4" : [2,4], 
    .... 
} 

我想是這樣的。

[ 
    [ 
    ["key1", "key3"], 
    [1,2,4], 
    ], 
    [ 
    ["key2", "key4"], 
    [2,4], 
    ], 
    ..... 
] 

基於唯一值對的鍵和值列表。我怎樣才能以pythonic的方式做到這一點?

回答

5

您可以反轉這樣的dictionnary:

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()] 
+0

「反轉」,其實。 – 2011-05-31 08:40:16

+1

請注意,從這裏到指定的結構OP只是'[[k,v] for k,v in new_dict.iteritems()]' – sverre 2011-05-31 08:44:13

+0

@Ignacio,sverre:謝謝,我用你的propoistions編輯我的答案 – 2011-05-31 08:52:56

1

這裏是一個列表理解做清潔工作:

[[[key for key in dictionary.keys() if dictionary[key] == value], value] 
    for value in unique(list(dictionary.values()))] 

哪裏unique可以是返回的獨特元素的功能名單。沒有默認設置,但有很多實現(here are some)。

0

請找我下面的代碼示例,如果它仍然是實際的給你:

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)