Skip to content Skip to sidebar Skip to footer

Iter, Values, Item In Dictionary Does Not Work

Having this python code edges = [(0, [3]), (1, [0]), (2, [1, 6]), (3, [2]), (4, [2]), (5, [4]), (6, [5, 8]), (7, [9]), (8, [7]), (9, [6])] graph = {0: [3], 1: [0], 2: [1, 6], 3: [2

Solution 1:

You are using Python 3; use dict.items() instead.

The Python 2 dict.iter* methods have been renamed in Python 3, where dict.items() returns a dictionary view instead of a list by default now. Dictionary views act as iterables in the same way dict.iteritems() do in Python 2.

From the Python 3 What's New documentation:

  • dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).
  • Also, the dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are no longer supported.

Also, the .next() method has been renamed to .__next__(), but dictionary views are not iterators. The line graph.iteritems().next() would have to be translated instead, to:

current = next(iter(graph.items()))

which uses iter() to turn the items view into an iterable and next() to get the next value from that iterable.

You'll also have to rename the next variable in the while loop; using that replaces the built-in next() function which you need here. Use next_ instead.

The next problem is that you are trying to use current as a key in cycles, but current is a tuple of an integer and a list of integers, making the whole value not hashable. I think you wanted to get just the next key instead, in which case next(iter(dict)) would give you that:

while graph:
    current= next(iter(graph))
    cycle= [current]
    cycles[current] =cycle
    while currentin graph:
        next_ = graph[current][0]
        del graph[current][0]
        if len(graph[current]) ==0:
            del graph[current]
        current= next_
        cycle.append(next_)

This then produces some output:

>>>cycles
{0: [0, 3, 2, 1, 0], 2: [2, 6, 5, 4, 2], 6: [6, 8, 7, 9, 6]}

Post a Comment for "Iter, Values, Item In Dictionary Does Not Work"