Iterating through nested dictionaries

Posted by Framester on Stack Overflow See other posts from Stack Overflow or by Framester
Published on 2012-11-14T16:41:02Z Indexed on 2012/11/14 17:00 UTC
Read the original article Hit count: 406

Filed under:
|
|

I want to write an iterator for my 'toy' Trie implementation.

Adding already works like this:

class Trie:
    def __init__(self):
        self.root = dict()
        pass
    def add(self, string, value):
        global nops
        current_dict = self.root
        for letter in s:
           nops += 1
           current_dict = current_dict.setdefault(letter, {})
        current_dict = current_dict.setdefault('value', value)              
        pass

The output of the adding looks like that:

trie = Trie()
trie.add("hello",1)
trie.add("world",2)
trie.add("worlds",12)
print trie.root
{'h': {'e': {'l': {'l': {'o': {'value': 1}}}}}, 'w': {'o': {'r': {'l': {'d': {'s': {'value': 2}, 'value': 2}}}}}}

I know, that I need a __iter__ and next method.

def __iter__(self):
    self.root.__iter__()
    pass

 def next(self):
    print self.root.next()

But AttributeError: 'dict' object has no attribute 'next'. How should I do it?

[Update] In the perfect world I would like the output to be one dict with all the words/entries with their corresponding values.

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary