が、私はfolowingフォームのリストを持っている:一覧 - 例外TypeError:非ハッシュタイプ: '辞書'
oldlist = [{'x': {'a':1,'b':2}, 'y':2},{'x':{'a':6,'b':7}, 'y':2},{'x':{'a':1,'b':2}, 'y':3},{'x':{'a':1,'b':2}, 'y':2},{'x':{'a':10,'b':11}, 'y':4}]
final = [{'x':{'a':1,'b':2},'y':[2,3,2],'count':3},{'x':{'a':6,'b':7},'y':[2],'count':1},{'x':{'a':10,'b':11},'y':[4],'count':1}]
に変換する
私は
を試してみましたoldlist = [{'x': {'a':1,'b':2}, 'y':2},{'x':{'a':6,'b':7}, 'y':2},{'x':{'a':1,'b':2}, 'y':3},{'x':{'a':1,'b':2}, 'y':2},{'x':{'a':10,'b':11}, 'y':4}]
list1=[]
list2=[]
list3=[]
s = set([d['x'] for d in oldlist])
news=list(s)
for item in oldlist:
if item['x'] == news[0]:
list1.append(item['y'])
if item['x'] == news[1]:
list2.append(item['y'])
if item['x'] == news[2]:
list3.append(item['y'])
final=[]
dic1 = {'x':news[0],'y':list1,'count':len(list1)}
dic2 = {'x':news[1],'y':list2,'count':len(list2)}
dic3 = {'x':news[2],'y':list3,'count':len(list3)}
final.append(dic1)
final.append(dic2)
final.append(dic3)
print final
取得
s = set([d['x'] for d in oldlist])
TypeError: unhashable type: 'dict'
これを行う簡単な方法はありますか?ここで私はxが3つの値しか持てないことを知っていたので、3つの変数list1、list2、list3を作成しました。 xが他にもいくつかの値を持つことができ、私はfinalのような辞書の同様のリストを見つけなければなりません!それはまた、文字列のために働く必要があります!
編集:これを試しました。しかし、それはすべての非ハッシュの種類がある集合関数は文字列のみ、番号、
データ型リストのようなタプルなど、辞書のように、hashable
オブジェクトを扱うことができ、ひいてはセット機能はできません
s = list(frozenset(oldlist[0]['x'].items()))
print s
for item in oldlist:
s.append(frozenset(item['x'].items()))
エラーが –