如何通过map或lambda函数用键提取dict的值

时间:2014-03-06 03:51:28

标签: python lambda

现在我有了一个字典:

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

1 个答案:

答案 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)]