Iter through dictionary in Python

I am still doing the Google foo-bar problem and need more dictionary operations. I have always doubt the way I iterate through a dictionary: first store a key in a list then iterate through the dictionary in a for loop, is really bad and I want to find a better way. It is called item().

An example:

“””python

knights = {‘gallahad’: ‘the pure’, ‘robin’: ‘the brave’} for k, v in knights.items(): … print(k, v) … gallahad the pure robin the brave “””

.item() generates a list of tuple. This is potentially very memory consuming but would be very fast for loop up. There is another method called iteritem() in python3 and it will return a generator. It is faster if you only want to iterate since the whole list is never generated.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax