Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 iteritems have to call s.keys() 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).

like image 598
CppLearner Avatar asked Sep 04 '12 19:09

CppLearner


1 Answers

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.

like image 146
Martijn Pieters Avatar answered Nov 03 '22 00:11

Martijn Pieters