CppLearner CppLearner - 1 year ago 96
Python Question

Make a simple Python dictionary generator

Here is a sample code basically doing an iteration.

>>> d = {'lol': {'12': '3', '35':''}, 'w': {'12': '3', '35':''}}

>>> def iteritems(s):
... keys = s.keys()
... for key in keys:
... yield key, s[key]
>>> for k, v in iteritems(d):
... print k, v
w {'12': '3', '35': ''}
lol {'12': '3', '35': ''}

This is a valid generator. But the generator
have to call
to cache all the keys in the dictionary. If the dictionary is large (over 100 items), that's not memory efficient.

But since dictionary is not an ordered structure, I assume that getting that list of keys is a must.

One may argue: the number of keys is far less than the number of items counting keys and values.

Any suggestion? Or better way (and of course I need to support nested iteation but that's another thing).

Answer Source

Use .iterkeys() in python 2.x; in python 3.x, .keys() is a view and not a new list. In python 2.7, you can also use the viewkeys() method to get the same thing.

There is an equivalent .iteritems() method, making your utility method redundant. :-) The same remarks apply here for python 3.x and 2.7, see the documentation supplied.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download