0
the d1 is  defaultdict(<type 'list'>, {'A': [4, 4, 4, 4], 'S': [1]})
the d2 is  defaultdict(<type 'list'>, {'A': [4, 4, 4], 'B': [2], '[]': [4, 4]})

これらの 2 つの辞書を 1 つにマージするにはどうすればよいですか?

期待される出力は

the d3 is  defaultdict(<type 'list'>, {'A': [4], 'B': [2], 'S':[1] ,'[]': [4]})

結果の辞書では、複数の値を1つにする必要があります

4

3 に答える 3

2

セットは重複した要素を保持しないためset、属性としてa を使用する必要があります。default_factory

d1 = defaultdict(set)

defaultdict既存の を useに変換するにはsets、次を試してください。

defaultdict(set, {key: set(value) for key, value in d1.iteritems()})

古い Python バージョンの場合:

defaultdict(set, dict((key, set(value)) for key, value in d1.iteritems()))
于 2012-08-04T18:23:45.807 に答える
0

以下はあなたが望むことをします:

from collections import defaultdict

d1 = defaultdict(list, {'A': [4, 4, 4, 4], 'S': [1], 'C': [1, 2, 3, 4]})
print 'the d1 is ', d1
d2 = defaultdict(list, {'A': [4, 4, 4], 'B': [2], '[]': [4, 4], 'C': [1, 2, 3]})
print 'the d2 is ', d2

d3 = defaultdict(list, dict((key, set(value) if len(value) > 1 else value)
                                for key, value in d1.iteritems()))
d3.update((key, list(d3[key].union(set(value)) if key in d3 else value))
                                for key, value in d2.iteritems())
print
print 'the d3 is ', d3

出力:

the d1 is  defaultdict(<type 'list'>, {'A': [4, 4, 4, 4], 'S': [1], 'C': [1, 2, 3, 4]})
the d2 is  defaultdict(<type 'list'>, {'A': [4, 4, 4], 'C': [1, 2, 3], 'B': [2], '[]': [4, 4]})

the d3 is  defaultdict(<type 'list'>, {'A': [4], 'S': [1], 'B': [2], 'C': [1, 2, 3, 4], '[]': [4, 4]})

'C'私は両方d1にキーを付けたリストを追加しd2、あなたの質問に記載されていない可能性に対して何が起こるかを示すことに注意してください-それがあなたが起こりたいことであるかどうかはわかりません。

于 2012-08-05T02:27:28.357 に答える
0

試す:

d1.update(d2)
for val in d1.values():
    if len(val) > 1:
        val[:] = [val[0]]
于 2012-08-04T18:23:46.420 に答える