Ja. L Ja. L - 6 months ago 29
Python Question

Make dict comprehension return by reference

  • I have following dictionary:
    original = {a:1, b:2}

  • I then run dict comprehension:
    extracted = {k:v for (k,v) in original.items() if k == 'a'}

  • The following dict is returned:

  • If I mutate
    extracted['a'] = 2
    will still be equal to


Is there a way to make the above dict comprehension return by reference? For example
extracted['a'] = 2
would result in
original['a'] = 2

I would prefer not to involve alteration of the

Answer Source

This can be done even with immutable values, if your new dictionary is of a custom type with the desired logic added:

class MappedDict(dict):
    def __init__(self, orig, *args, **kwargs):
        self.__orig = orig
        dict.__init__(self, *args, **kwargs)
    def __setitem__(self, k, v):
        self.__orig[k] = v
        return dict.__setitem__(self, k, v)

d = {'a': 1, 'b': 2}
md = MappedDict(d, {k: v*2 for (k,v) in d.items()})

...will leave both d and md having 'a' having the value 5, whereas b will differ (being 2 in the former and 4 in the latter).

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