从字典创建元组列表?

时间:2012-06-07 02:50:51

标签: python dictionary casting nested tuples

我有一个简单的字典:

{"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

我如何创建这个元组列表?

6 个答案:

答案 0 :(得分: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)

<强>输出:

[('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')]

答案 1 :(得分: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()]

答案 2 :(得分: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())

答案 3 :(得分: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关于如何以简单方式执行此操作的答案:)

答案 4 :(得分: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]]

答案 5 :(得分: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')]