toby1kenobi
toby1kenobi

Reputation: 13

Turning a Python dict with mutiple values in to a list with every key value pair

I have a dictionary with changing number of values per key, e.g.

my_dict = {'a':['e','f'],'b':['g'],'c':[]}

I would like to extract every key value pair in a list, i.e.

[('a','e'),('a','f'),('b','g')]

So 'c' should not be a part of the list since it has no value associated.

Upvotes: 0

Views: 62

Answers (2)

jpp
jpp

Reputation: 164623

This is possible with a list comprehension:

my_dict = {'a':['e','f'],'b':['g'],'c':[]}

res = [(k, w) for k, v in my_dict.items() for w in v]

# [('a', 'e'), ('a', 'f'), ('b', 'g')]

For academic purposes here is a slightly different algorithm:

from itertools import zip_longest

my_dict = {'a':['e','f'],'b':['g'],'c':[]}

res = [(i, j) for k, v in my_dict.items()
       for i, j in zip_longest(k, v, fillvalue=k) if v]

# [('a', 'e'), ('a', 'f'), ('b', 'g')]

Upvotes: 2

IMCoins
IMCoins

Reputation: 3306

# your original data
my_dict = {'a':['e','f'],'b':['g'],'c':[]}

# your list of tuples.
new_list = []
for k, v in my_dict.iteritems(): # .items() in python 3x
    for item in v:
        # For each element in the list, append a tuple (key, current list item) to your output.
        new_list.append((k, item))

Outputs:

# [('a', 'e'), ('a', 'f'), ('b', 'g')]

Upvotes: 1

Related Questions