Fixed `swap` between dict items.

This commit is contained in:
Fabio Caccamo 2022-07-15 23:54:34 +02:00
parent 244f6056bc
commit 37fed12485
2 changed files with 21 additions and 1 deletions

View File

@ -4,4 +4,8 @@
def swap(d, key1, key2): def swap(d, key1, key2):
if key1 == key2: if key1 == key2:
return return
d[key1], d[key2] = d[key2], d[key1] val1 = d[key1]
val1 = val1.copy() if isinstance(val1, dict) else val1
val2 = d[key2]
val2 = val2.copy() if isinstance(val2, dict) else val2
d[key1], d[key2] = val2, val1

View File

@ -2081,6 +2081,22 @@ b:
b = benedict(d) b = benedict(d)
b.swap("a.y", "b.y") b.swap("a.y", "b.y")
b.swap("b.x", "c.x") b.swap("b.x", "c.x")
r = {
"a": {
"x": 1,
"y": 2,
},
"b": {
"x": 3,
"y": 1,
},
"c": {
"x": 2,
"y": 3,
},
}
self.assertEqual(b, r)
b.swap("a", "c") b.swap("a", "c")
r = { r = {
"a": { "a": {