2012-06-07 166 views
0

我有一個簡單的解釋:從字典中創建元組列表?

{"keyy":{"key": "value", "cey": "value"}, "kaye":{"key": "value"}} 

,我想編碼爲「上下文感知」的元組:

[("keyy","key","value"), ("keyy","cey","value"), ("kaye","key","value")] 

我嘗試用ValueError異常:值過多解壓

if __name__=='__main__': 
    mydict={"keyy":{"key": "value", "cey": "value"}, "kaye":{"key", "value"}} 
    mytuplelist=[tuple(k,v,val) for (k,v) in [(key,val) for (key,val) in mydict]] 
    print mytuplelist 

我該如何去創建這個元組列表?

+0

我會用我的嘗試編輯它 – user1438003

+0

'tuple(k,v,val)'應該是'(k,v,val)'next –

+0

是的,我知道,只是想明確地表明我是什麼試圖去做。 – user1438003

回答

3

使用列表理解:

mydict={"keyy":{"key": "value", "cey": "value"}, "kaye":{"key": "value"}} 

mytuplelist=[(key,y,mydict[key][y]) for key in mydict for y in mydict[key]] 

print (mytuplelist) 

輸出T:

[('keyy', 'cey', 'value'), ('keyy', 'key', 'value'), ('kaye', 'key', 'value')] 

使用簡單的for-in循環:

dic={"keyy":{"key": "value", "cey": "value"}, "kaye":{"key": "value"}} 
lis=[] 
for x in dic: 
    for y in dic[x]: 
     lis.append((x,y,dic[x][y])) 
print(lis) 

輸出:

[('keyy', 'cey', 'value'), ('keyy', 'key', 'value'), ('kaye', 'key', 'value')] 
+0

謝謝,這(和另外兩個)工作! :D - 爲了幫助我決定接受哪一個,你認爲你們中的任何一個人都可以把它歸結爲一行嗎? :P – user1438003

+0

@ user1438003我使用列表理解,它是一個班輪。 –

+0

完美:D - 謝謝 – user1438003

2

我喜歡發電機此:

mydict = {"keyy":{"key": "value", "cey": "value"}, "kaye":{"key": "value"}} 

def unnest(d): 
    for outerkey in d.iterkeys(): 
     for innerkey, value in d[outerkey].iteritems(): 
      yield outerkey, innerkey, value 

mytuplelist = list(unnest(mydict)) 

或者,你當然可以把它放在一個列表理解:

mytuplelist = [(outerkey, innerkey, value) for outerkey in mydict.iterkeys() 
       for (innerkey, value) in mydict[outerkey].iteritems()] 
0

要修復代碼:

mydict={"keyy":{"key": "value", "cey": "value"}, "kaye":{"key" : "value"}} 
mytuplelist = [(outer, inner, val) for outer, d in mydict.iteritems() 
      for inner, val in d.iteritems()] 
print mytuplelist 

見kindall對如何做到這一點的簡單方法:)

+0

謝謝,我現在已經學會了iteritems()是如何工作的:D – user1438003

1

下面的例子將作爲您指定創建的元組的列表答案:

mydict = {"keyy":{"key": "value", "cey": "value"}, "kaye":{"key": "value"}} 
tuplelist = [] 
for outer, dct in mydict.iteritems(): 
    tuplelist.extend((outer, key, val) for key, val in dct.iteritems()) 
0

通過糾正你的拼寫錯誤(缺少最後的嵌套:快譯通,的「過多的物品,以解包」可能的原因之一),你可以回到你的列表理解:

dict1 = {"keyy":{"key": "value", "cey": "value"}, "kaye":{"key": "value"}} 

print [(key1, key2, dict1[key1][key2]) for key1 in dict1 for key2 in dict1[key1]] 
0

使用列表理解

>>> D={"keyy":{"key": "value", "cey": "value"}, "kaye":{"key": "value"}} 
>>> [(i,)+j for i in D for j in D[i].iteritems()] 
[('keyy', 'cey', 'value'), ('keyy', 'key', 'value'), ('kaye', 'key', 'value')]