Joe
Joe

Reputation: 909

Graph dictionary outputs RuntimeError

I have a dictionary of lists:

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

in which some of the values are not present as keys. I want to add all values, as keys with empty lists, which are not present in keys. Current I am attempting to do this as follows:

for keys, values in g.items():
    for value in values:
        if value not in keys:
            g[value] = []

Running the above code gives a traceback: RuntimeError: dictionary changed size during iteration. I checked other related questions in Stackoverflow but couldn't find a related task.

I look to have the following output:

{'a': ['b', 'c'], 'b': ['a', 'd', 'e'], 'c': [], 'd': [], 'e': []}

Upvotes: 0

Views: 23

Answers (1)

fxdeaway
fxdeaway

Reputation: 165

Solution

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

for keys, values in list(g.items()):
    for value in values:
        if value not in g:
            g[value] = []

print(g)

Explanation

Please refer to this Stack Overflow post for more information regarding using list(). Also, your conditional should check if value is in g, not in keys.

Upvotes: 1

Related Questions