[英]Python3 dictionary merge based on values
我有一本由{key: value}
組成的字典。
我從這本詞典中選擇了一組鍵。
我想使用{keyA: set of all keys wich have the same value as keyA}
一個新字典。
我已經有一個解決方案:有沒有更快的方法呢?
對我來說似乎很慢,我想我不是這種情況下唯一的一個!
for key1 in selectedkeys:
if key1 not in seen:
seen.add(key1)
equal[key1] = set([key1])#egual to itself
for key2 in selectedkeys:
if key2 not in seen and dico[key1] == dico[key2]:
equal[key1].add(key2)
seen.update(equal[key1])
嘗試這個
>>> a = {1:1, 2:1, 3:2, 4:2}
>>> ret_val = {}
>>> for k, v in a.iteritems():
... ret_val.setdefault(v, []).append(k)
...
>>> ret_val
{1: [1, 2], 2: [3, 4]}
def convert(d):
result = {}
for k, v in d.items(): # or d.iteritems() if using python 2
if v not in result:
result[v] = set()
result[v].add(k)
return result
或者如果您足夠小心不要稍后再訪問任何非密鑰,則只使用collections.defaultdict(set)
:-)
由於您從原始詞典中選擇了一組鍵。 我們可以根據您的需要修改@Nilesh解決方案。
a = {1:1, 2:1, 3:2, 4:2}
keys = [1, 3] # lets say this is the list of keys
ret_val = {}
for i in keys:
for k,v in a.items():
if a[i]==v:
ret_val.setdefault(i, []).append(k)
print (ret_val)
{1: [1, 2], 3: [3, 4]}
@Patrick Haugh在評論中說過:
d=your dictionary
s=set(d.values())
d2={i:[] for i in s}
for k in d:
d2[d[k]].append(k)
所以,你想創建一個映射的字典key
為“一組具有相同值的所有鍵的key
”在給定的源字典中的每個選擇鍵。
因此,如果源詞典是:
{'a': 1, 'b': 2, 'c': 1, 'd': 2, 'e': 3, 'f': 1, 'g': 3)
並且所選鍵為a
, b
和e
,結果應為:
{'a': {'a', 'c', 'f'}, 'e': {'g', 'e'}, 'b': {'b', 'd'}}
實現此目的的一種方法是使用defaultdict為鍵表構建值,然后使用該值從指定鍵構建所需的結果:
from collections import defaultdict
def value_map(source, keys):
table = defaultdict(set)
for key, value in source.items():
table[value].add(key)
return {key: table[source[key]] for key in keys}
source = {'a': 1, 'b': 2, 'c': 1, 'd': 2, 'e': 3, 'f': 1, 'g': 3)
print(value_map(source, ['a', 'b', 'e']))
輸出:
{'a': {'a', 'c', 'f'}, 'e': {'g', 'e'}, 'b': {'b', 'd'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.