Python doesn't have variables

10/5/22

My journey here starts with a task:

Turning this

{
    "firstdata": {
        "0": {"name": "ansel"}, 
        "1": {"name": "adams"}
    }
}

…into this

{
    "firstdata": [
        {"name": "ansel"},
        {"name": "adams"}
    ]
}

Here’s the solution with some recursion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
datadict = {
    "firstdata": {
        "0": {"name": "ansel"}, 
        "1": {"name": "adams"}
    }
}

def walk(node):
    for key, val in node.items():
        if isinstance(val, dict):
            if all([x.isdigit() for x in val.keys()]):
                node[key] = [y for _, y in val.items()]
            walk(val)

# Note this doesn't return anything.
# The input dictionary is modified in place
walk(datadict)
datadict

Which led me to learning about this:

1
2
3
4
5
6
7
8
9
a = 15
b = 15
a is b
>>> True

a = 1000
b = 1000
a is b
>>> False