在python中,如何将列表的dict转换为键和值的元组列表?

在python中,如何将列表的dict转换为键和值的元组列表?,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,我有一份清单如下: y = {'a':[1,2,3], 'b':[4,5], 'c':[6]} x = reduce(lambda p,q:p+q, map(lambda (u,v):[(u,t) for t in v], y.iteritems())) 我想将dict转换为一个元组列表,其中每个元素都是一个元组,包含dict的一个键和值列表中的一个元素: x = [ ('a',1),('a',2),('a',3), ('b',4),('b',5), ('c',6)

我有一份清单如下:

y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
x = reduce(lambda p,q:p+q, map(lambda (u,v):[(u,t) for t in v], y.iteritems()))
我想将dict转换为一个元组列表,其中每个元素都是一个元组,包含dict的一个键和值列表中的一个元素:

x = [
    ('a',1),('a',2),('a',3),
    ('b',4),('b',5),
    ('c',6)
    ]
我的代码如下:

y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
x = reduce(lambda p,q:p+q, map(lambda (u,v):[(u,t) for t in v], y.iteritems()))

这样的代码似乎很难读懂,所以我想知道是否有类似python的方法,或者更准确地说,列表理解中的一种方法可以做到这一点?

您可以这样做

>>> y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
>>> [(i,x) for i in y for x in y[i]]
[('a', 1), ('a', 2), ('a', 3), ('c', 6), ('b', 4), ('b', 5)]

另一种方法,但不一定更具可读性或通俗易懂:

>>> from itertools import izip_longest
>>> y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
>>> [tuple(izip_longest(k, v, fillvalue=k)) for k, v in y.items()]
[(('a', 1), ('a', 2), ('a', 3)), (('c', 6),), (('b', 4), ('b', 5))]