-
Notifications
You must be signed in to change notification settings - Fork 107
Operations
Chris Griffith edited this page Apr 9, 2020
·
1 revision
Traditional dictionary updates are destructive to sub dictionaries, merge update on the other hand will add the two sub dictionaries together.
box_1 = Box(val={'important_key': 1})
box_2 = Box(val={'less_important_key': 2})
box_1.merge_update(box_2)
print(box_1)
# {'val': {'important_key': 1, 'less_important_key': 2}}
box_1 = Box(val={'important_key': 1})
box_2 = Box(val={'less_important_key': 2})
box_1.update(box_2)
print(box_1)
# {'val': {'less_important_key': 2}}
In Python 3.9 they will add the ability to update
two dictionaries using the union
operator |
, but boxes can already do that!
box_1 = Box(cast={'Scooby-Doo': True, 'Velma': True, 'Shaggy': True},
props={'Mystery Machine': True})
box_2 = Box(props={}, set='Desert')
box_1 | box_2
# <Box: {'cast': {'Scooby-Doo': True, 'Velma': True, 'Shaggy': True},
# 'props': {}, 'set': 'Desert'}>
Box also supports in place union using |=
Addition uses the internal merge_update
instead of the dictionary update
box_1 = Box(cast={'Scooby-Doo': True, 'Velma': True, 'Shaggy': True},
props={'Mystery Machine': True})
box_2 = Box(props={}, set='Desert')
box_1 + box_2
# <Box: {'cast': {'Scooby-Doo': True, 'Velma': True, 'Shaggy': True},
# 'props': {'Mystery Machine': True}, 'set': 'Desert'}>
Box also supports in place addition using +=
box_1 = Box(cast={'Scooby-Doo': True, 'Velma': True, 'Shaggy': True},
props={'Mystery Machine': True})
box_2 = Box(props={}, set='Desert')
box_1 - box_2
# <Box: {'cast': {'Scooby-Doo': True, 'Velma': True, 'Shaggy': True},
# 'props': {'Mystery Machine': True}}>
Notice that box doesn't delete the entire sub dictionary when a key matches, but like merge_update
will do a recursive subtraction. So if something with the same key name exists lower, it them will be removed.
box_1 = Box(cast={'Scooby-Doo': True, 'Velma': True, 'Shaggy': True},
props={'Mystery Machine': True})
box_2 = Box(props={'Mystery Machine': 'Fully Loaded'}, set='Desert')
box_1 - box_2
# <Box: {'cast': {'Scooby-Doo': True, 'Velma': True, 'Shaggy': True}}>
These documents are for Box 5.0+