IsaacJ700
IsaacJ700

Reputation: 51

Python convert dictionary where keys have multiple values into list of tuples

I am trying to convert a dictionary into a list of tuples. I see that there are lots of similar posts on here, but I didn't see any with the same format that I am looking for. For example, I may be given the following as a dict:

{"A": ["B", "C", "D"], "B":["D"], "C":[], "D":["A"]}

And I want the output to look like a list with elements such as...

[('A', 'B'), ('A", 'C'), ('A', 'D'), ('B', 'D'), ('D', 'A')]

where the key is set with the corresponding values as their own tuples.

So for the following, I am writing the function find_par where it takes in a dict, and 2 strings such as "A" and "D". Ultimately I'm what this function does is try to find the parent node of the vert parameter. I figured if I can get a list, I can loop over the list continuously checking the 2nd element and once it matches vert, I can return the first element because that would be the parent. Otherwise I would return nothing.

def find_par(tree, root, vert):

if root == vert:
    return []
else:
    for key, value in tree.items():
        temp = [key,value]
        print (temp)

This code produces the following output with the dict {"A": ["B", "C"], "B":["D"], "C":[], "D":[]} provided:

['A', ['B', 'C']]
['B', ['D']]
['C', []]
['D', []]

Again, it should look like [('A', 'B'), ('A', 'C'), ('B', 'D'),...]

Upvotes: 0

Views: 2239

Answers (3)

krewsayder
krewsayder

Reputation: 446

I have stored your dict as variable z.

[(a, b) for a in z for b in z[a]]

Below I'll explain how this nesting of list comprehension works:

You're taking every key in the dictionary with for a in z and matching it with every value in the list associated with z[a] using for b in z[a]. You can see at the beginning of the statement I create a tuple.

Upvotes: 0

Marios Nikolaou
Marios Nikolaou

Reputation: 1336

Check this.

dict1 = {"A": ["B", "C"], "B":["D"], "C":[], "D":[]}

for key, values in dict1.items():
    for i in values:
        print([key,i])

 #prints ['A', 'B'],['A', 'C'],['B', 'D']

Upvotes: 0

blhsing
blhsing

Reputation: 106502

You can use a list comprehension to iterate over the items in the sub-list in each dict value (given your dict stored as variable d):

[(k, i) for k, l in d.items() for i in l]

This returns:

[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'D'), ('D', 'A')]

Upvotes: 2

Related Questions