现在我有了一个字典:
d = {'key1':
{'key11':1,
'key12':2},
'key2':
{'key21':3,
'key22':4}
}
如何将其提取到元组列表:
l = [('key1','key11',1),
('key1','key12',2),
('key2','key21',3),
('key2','key22',4)]
使用map或lambda函数
我的Python版本是Python2.7
答案 0 :(得分:2)
您可以使用列表推导来获得所需的输出
print [(k, k1, d[k][k1]) for k in d for k1 in d[k]]
<强>输出强>
[('key2', 'key22', 4),
('key2', 'key21', 3),
('key1', 'key12', 2),
('key1', 'key11', 1)]
如果您希望对输出进行排序,如问题所示,
print sorted([(k, k1, d[k][k1]) for k in d for k1 in d[k]])
<强>输出强>
[('key1', 'key11', 1),
('key1', 'key12', 2),
('key2', 'key21', 3),
('key2', 'key22', 4)]