Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a dict of lists to a list of tuples of key and value in python?

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?

like image 370
zako Avatar asked Mar 02 '15 10:03

zako


People also ask

How do I turn my dictionary into a list of tuples?

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.

Can you convert a key-value dictionary to list of lists?

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.

Can a tuple with a list be a key in a dictionary?

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.


1 Answers

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)]
like image 105
Avinash Raj Avatar answered Sep 25 '22 01:09

Avinash Raj