Python3字典基于值合并

问题描述 投票:0回答:5

我有一本由

{key: value}
组成的字典。

我从这本字典中选择一组键。

我想用

{keyA: set of all keys which 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])
python python-3.x dictionary merge
5个回答
1
投票

试试这个

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

1
投票
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)
:-)


0
投票

因此,您想要创建一个字典,对于给定源字典中的每个选定键,将

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

0
投票

因为您从原始字典中选择了一组键。我们可以根据您的目的修改@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]}

0
投票

这在@Patrick Haugh 的评论中有所表述:

d=your dictionary
s=set(d.values())
d2={i:[] for i in s}
for k in d:
    d2[d[k]].append(k)
© www.soinside.com 2019 - 2024. All rights reserved.