dict.items to accept optional iterable with keys to use

Sometimes you want a dict which is subset of another dict. It would nice if dict.items accepted an optional list of keys to return. If no keys are given - use default behavior - get all items. class NewDict(dict): def items(self, keys=()): """Another version of dict.items() which accepts specific keys to use.""" for key in keys or self.keys(): yield key, self[key] a = NewDict({ 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}) print(dict(a.items()))print(dict(a.items((1, 3, 5)))) vic@ubuntu:~/Desktop$ python test.py {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}{1: 'one', 3: 'three', 5: 'five'} Thanks for the attention. -- *Victor Varvariuc*

On Wed, Apr 4, 2012 at 1:07 AM, Victor Varvariuc <victor.varvariuc@gmail.com> wrote:
In that use case, why not just write a dict comprehension?: print({k: a[k] for k in (1, 3, 5)}) Completely explicit, and only a mere few characters longer. Cheers, Chris

On Wed, Apr 04, 2012 at 11:07:55AM +0300, Victor Varvariuc wrote:
Too trivial to bother with. # I want a list of keys/values: items = [(key, mydict[key]) for key in list_of_keys] # I want them generated on demand: iterable = ((key, mydict[key]) for key in list_of_keys) # I want a new dict: newdict = dict((key, mydict[key]) for key in list_of_keys) Both of those require that list_of_keys includes keys that do exist. If you want to skip missing keys: [(k,v) for (k,v) in mydict.items() if k in list_of_keys] To be even more efficient, use a set of keys instead of a list. -- Steven

Victor Varvariuc schrieb am Wed, 04. Apr 2012, um 11:07:55 +0300:
How about using `operator.itemgetter()`? from operator import itemgetter itemgetter(*keys)(my_dict) It will return a tuple of the values corresponding to the given keys. Cheers, Sven

On Wed, Apr 4, 2012 at 1:07 AM, Victor Varvariuc <victor.varvariuc@gmail.com> wrote:
In that use case, why not just write a dict comprehension?: print({k: a[k] for k in (1, 3, 5)}) Completely explicit, and only a mere few characters longer. Cheers, Chris

On Wed, Apr 04, 2012 at 11:07:55AM +0300, Victor Varvariuc wrote:
Too trivial to bother with. # I want a list of keys/values: items = [(key, mydict[key]) for key in list_of_keys] # I want them generated on demand: iterable = ((key, mydict[key]) for key in list_of_keys) # I want a new dict: newdict = dict((key, mydict[key]) for key in list_of_keys) Both of those require that list_of_keys includes keys that do exist. If you want to skip missing keys: [(k,v) for (k,v) in mydict.items() if k in list_of_keys] To be even more efficient, use a set of keys instead of a list. -- Steven

Victor Varvariuc schrieb am Wed, 04. Apr 2012, um 11:07:55 +0300:
How about using `operator.itemgetter()`? from operator import itemgetter itemgetter(*keys)(my_dict) It will return a tuple of the values corresponding to the given keys. Cheers, Sven
participants (4)
-
Chris Rebert
-
Steven D'Aprano
-
Sven Marnach
-
Victor Varvariuc