Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: {a:1}
  • If I mutate extracted['a'] = 2, original['a'] will still be equal to 1

Question:

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 original dictionary.


1 Answers

Your intended goal (of having a dictionary which, when updated, will also change the other dictionary from which it was derived) 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()})
md['a']=5

...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).

like image 83
Charles Duffy Avatar answered May 07 '26 22:05

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!