0

我有一个简单的字典:

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

我想编码为“上下文感知”元组:

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

我对ValueError: too many values to unpack的尝试:

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

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

4

6 回答 6

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')]
于 2012-06-07T03:03:45.243 回答
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()]
于 2012-06-07T03:01:59.870 回答
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())
于 2012-06-07T03:05:28.987 回答
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关于如何以简单方式执行此操作的答案:)

于 2012-06-07T03:04:12.520 回答
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]]
于 2012-06-07T03:11:31.080 回答
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')]
于 2012-06-07T03:11:36.013 回答