original = {a:1, b:2}extracted = {k:v for (k,v) in original.items() if k == 'a'}{a:1}extracted['a'] = 2, original['a'] will still be equal to 1Is 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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With