3 ms·
In case the values match you could supply a collision callback to define what to do, eg to add the values, d1 = {'a': 1} d2 = {'a': 2} d3 = {**d1, **d2,
by dstola 8y ago
In case the values match you could supply a collision callback to define what to do, eg to add the values,
d1 = {'a': 1}
d2 = {'a': 2}
d3 = {**d1, **d2, add_func)
def add_func(a, b):
return a+b
Or something along those lines
- rbanffy 8y agoWhy not raise a ValueError and let the programmer figure out what The Right Thing To Do is when you add two dicts that have the same key with a different value? I assume the same key with the same value would be OK, but I'm not really sure it's a good idea for it to be OK.
- zimablue 8y agoYou can't do value comparison without making dict item comparison a pissed in function or making dict values immutable. If you're doing something that really looks like a mathematical Union that will raise if there's any overlap then it's a really confusing abuse of notation. I don't think there's a way out.
- deleted 8y ago[deleted]
- mturmon 8y agoThat syntax doesn't make sense. The {**d1, **d2} idiom is just a clever mashup of Python's dictionary construction literal {}, and * * unpacking. That's why it only works with string-valued keys (which is a major limitation). Adding a third item to the dictionary literal would require special-casing the {} dictionary construction literal.
- dan-robertson 8y agoThat is one thing you could do to merge dicts. To expand on my last paragraph above, I think I would imagine the following operations (stupid syntax): a & b = { k: (a[k], b[k]) for k in a.keys() | b.keys() } a | b = { k: (a.get(k, None), b.get(k, None)) for k in a.keys() | b.keys() } a |& b = { k: (a.get(k,None), v) for k, v in b.items() } a &| b = { k: (v, b.get(k,None)) for k, v in a.items() } a |_| b = { k: only(a,b,k) for k in a.keys() | b.keys() } def only(a,b,k): if k in a && k in b: throw DuplicateKey(a,b,k) elseif k not in a && k not in b: assert(false) elseif k in a: return a[k] else: return b[k] This doesn’t work well if values can be None so maybe instead of pairs there should be objects Left(x), Right(y), and Both(x,y)