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.