0
key, values
(0, 1)
(0, 2)
(0, 6)
(0, 7)
(1, 0)
(1, 2)
(2, 1)
(2, 0)
(3, 4)
(3, 5)
(4, 3)
(5, 3)
(6, 0)
(7, 0)

我的 python 代码有问题。我想在 python 的字典中插入数据。我看到这样的错误:

N = len(g.nodes())

label_for_node = dict((i, v) for i, v in enumerate(g.nodes()))
node_for_label = dict((label_for_node[i], i) for i in range(N))


communities = dict((i, frozenset([i])) for i in range(N))
dq_dict = {}
H = MappedQueue()

partition = [[label_for_node[x] for x in c] for c in communities.values()]

dq_dict = dict(
        (i, dict( (j)
            for j in [ node_for_label[u] for u in g.neighbors(label_for_node[i])] if j != i)) 
                    for i in range(N))

TypeError: cannot convert dictionary update sequence element #0 to a sequence

问题是我想在索引与前一个索引相同时插入 dict。我想这样输出:

{0: {1, 2, 6, 7}, 
1: {0, 2}, 
2: {1, 0}, 
3: {4, 5}, 
4: {3}, 
5: {3}, 
6: {0}, 
7: {0}}
4

3 回答 3

1
def dictify(data):
    result = dict()
    for key, value in data:
        if key in result:
            result[key].add(value)
        else:
            result[key] = set([value])
    return result

例子

>>> data
[(0, 1), (0, 2), (0, 6), (0, 7), (1, 0), (1, 2), (2, 1), (2, 0), (3, 4), (3, 5), (4, 3), (5, 3), (6, 0), (7, 0)]
>>> dictify(data)
{0: {1, 2, 6, 7},
 1: {0, 2},
 2: {0, 1},
 3: {4, 5},
 4: {3},
 5: {3},
 6: {0},
 7: {0}}

您也可以使用collections.defaultdict

from collections import defaultdict
def dictify(data):
    result = defaultdict(set)
    for key, value in data:
        result[key].add(value)
    return result
于 2020-02-24T16:52:25.123 回答
0

您可以使用collections.defaultdict.

from collections import defaultdict
l = [(0, 1), (0, 2), (0, 6), (0, 7), (1, 0), (1, 2), (2, 1), (2, 0), (3, 4), (3, 5), (4, 3), (5, 3), (6, 0), (7, 0)]
new_dict=defaultdict(set)
for k,v in l:
    new_dict[k].add(v)

defaultdict(set,
            {0: {1, 2, 6, 7},
             1: {0, 2},
             2: {0, 1},
             3: {4, 5},
             4: {3},
             5: {3},
             6: {0},
             7: {0}})
于 2020-02-24T16:56:18.197 回答
0

Dictionary 的setdefault方法正是为此目的而构建的。它接受两个参数,即键值和键的默认值(如果键尚未插入字典中)。然后它返回与键对应的值。

l = [(0, 1), (0, 2), (0, 6), (0, 7), (1, 0), (1, 2), (2, 1), (2, 0), (3, 4), (3, 5), (4, 3), (5, 3), (6, 0), (7, 0)]
z={}
for k,v in l:
    z.setdefault(k,set()).add(v)
于 2020-02-24T17:05:54.367 回答