I have a dict of lists like this:
y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
I want to convert the dict into a list of tuples, each element of which is a tuple containing one key of the dict and one element in the value list:
x = [
('a',1),('a',2),('a',3),
('b',4),('b',5),
('c',6)
]
My code is like this:
x = reduce(lambda p,q:p+q, map(lambda (u,v):[(u,t) for t in v], y.iteritems()))
Such a code seems hard to read, so I wonder if there is any pythonic way, or more precisely, a way in list comprehension to do such thing?
Convert a Python Dictionary to a List of Tuples Using the List Function. One of the most straightforward and Pythonic ways to convert a Python dictionary into a list of tuples is to the use the built-in list() function. This function takes an object and generates a list with its items.
Method #1: Using loop + items() This brute force way in which we can perform this task. In this, we loop through all the pairs and extract list value elements using items() and render them in a new list.
A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.
You could do something like this,
>>> 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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With