2016-08-29 14 views
0

私は別の "タイプ" - >変更と削除で辞書を持っています。 私はこれをユニークにしたいと思います。私は、「キーのカップル」に基づいて独自のリストを取得できますか複数のキーに基づいたユニークな辞書

dict((v['target']['id'],v) for v in myDict).values() 

[ 
{'type': 'deleted', 'target': {'foo': {'value': ''}, 'id': u'1'}}, 
{'type': 'deleted', 'target': {'foo': {'value': ''}, 'id': u'2'}}, 
{'type': 'deleted', 'target': {'foo': {'value': ''}, 'id': u'3'}} 
] 

:私はこれを行うユニークなリストを達成するために

myDict = 
[ 
{'type': 'deleted', 'target': {'id': u'1', 'foo': {'value': ''}}}, 
{'type': 'modified', 'target': {'id': u'1', 'foo': {'value': ''}}}, 
{'type': 'deleted', 'target': {'id': u'1', 'foo': {'value': ''}}}, 

{'type': 'deleted', 'target': {'id': u'2', 'foo': {'value': ''}}}, 
{'type': 'deleted', 'target': {'id': u'2', 'foo': {'value': ''}}}, 
{'type': 'deleted', 'target': {'id': u'2', 'foo': {'value': ''}}}, 

{'type': 'deleted', 'target': {'id': u'3', 'foo': {'value': ''}}}, 
{'type': 'modified', 'target': {'id': u'3', 'foo': {'value': ''}}}, 
{'type': 'deleted', 'target': {'id': u'3', 'foo': {'value': ''}}} 
] 

私は両方のタイプが必要です。私の期待される結果は:

[ 
{'type': 'deleted', 'target': {'foo': {'value': ''}, 'id': u'1'}}, 
{'type': 'modified', 'target': {'foo': {'value': ''}, 'id': u'1'}}, 

{'type': 'deleted', 'target': {'foo': {'value': ''}, 'id': u'2'}}, 
{'type': 'modified', 'target': {'foo': {'value': ''}, 'id': u'2'}}, 

{'type': 'deleted', 'target': {'foo': {'value': ''}, 'id': u'3'}} 
] 

答えて

1

私はあなたの質問を理解しましたが、これはあなたが欲しいものですか?

from collections import defaultdict 
import json 

my_list = [ 
    {'type': 'deleted', 'target': {'id': u'1', 'foo': {'value': ''}}}, 
    {'type': 'modified', 'target': {'id': u'1', 'foo': {'value': ''}}}, 
    {'type': 'deleted', 'target': {'id': u'1', 'foo': {'value': ''}}}, 

    {'type': 'deleted', 'target': {'id': u'2', 'foo': {'value': ''}}}, 
    {'type': 'deleted', 'target': {'id': u'2', 'foo': {'value': ''}}}, 
    {'type': 'deleted', 'target': {'id': u'2', 'foo': {'value': ''}}}, 

    {'type': 'deleted', 'target': {'id': u'3', 'foo': {'value': ''}}}, 
    {'type': 'modified', 'target': {'id': u'3', 'foo': {'value': ''}}}, 
    {'type': 'deleted', 'target': {'id': u'3', 'foo': {'value': ''}}} 
] 

out = defaultdict(set) 

for v in my_list: 
    out[v["type"]].add(json.dumps(v["target"], sort_keys=True)) 

result = [] 
for k, v in out.iteritems(): 
    for vv in out[k]: 
     result.append({ 
      "type": k, 
      "target": json.loads(vv) 
     }) 

print out 
print len(out["deleted"]) 
print len(out["modified"]) 
+0

こんにちは。いいえ、print len(out ["deleted"])の結果は7です。重複するエントリがあります。私は "キーペア"に基づいてユニークな辞書が必要です。タイプとターゲット – saromba

+0

@sarombaまあ、私は私の答えを編集しました! – BPL

+0

Thx。私はそれを使って作業することができます。 – saromba

関連する問題