0

Say I have this nested dict:

[
  {
    "id": 1,
    "name": "Mammals",
    "animals": [
        {
            "id": 1,
            "name": "Chinchilla",
            "extinct": False
        },
        {
            "id": 2,
            "name": "Wooly Mammoth",
            "extinct": True
        },
        ...
    ]
  },
  ...
]

But Oh No! The Chinchilla has gone extinct! Now I have another, smaller, dict of identical format which represents updates to the extinct value on one or more members:

[
  {
    "id": 1,
    "name": "Mammals",
    "animals": [
        {
            "id": 1,
            "name": "Chinchilla",
            "extinct": True
        },
        ...
    ]
  },
  ...
]

I could start nesting for loops, throw in an if or two to compare id values, and tackle this pretty easily - but that many layers of nesting just feels bad to do. Is there a better and/or more pythonic way to do this?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
David Perry
  • 1,324
  • 5
  • 14
  • 31
  • 1
    Not really. Unless you want to use a library which contains all the nested loops and comparisons and provides a different API. – mkrieger1 Aug 10 '23 at 18:46
  • 4
    Nested for's is pretty reasonable here. If you plan to make multiple updates, then indexing the nested dict once and doing a shorter index based lookup is reasonable. Or change the format. This could be stored in a database or perhaps even loaded into a pandas table after flattening . – tdelaney Aug 10 '23 at 18:52
  • I would start by thinking if it made sense to turn this into one large dictionary rather than lists of lists. – JonSG Aug 10 '23 at 18:57
  • 1
    You could convert that outer list into a dict whose key is each entry's id. Then do the same with each animals list. Now lookup is by id. – tdelaney Aug 10 '23 at 18:59
  • Sort of related: [Update value of a nested dictionary of varying depth](/q/3232943/4518341) – wjandrea Aug 10 '23 at 19:16
  • "but that many layers of nesting just feels bad to do." *but that is an issue with your data as it exists*. If you want to keep this format, then this is what you need to do. That isn't to say you couldn't change the way your data is organized. – juanpa.arrivillaga Aug 10 '23 at 19:19
  • 1
    The [glom](https://pypi.org/project/glom) package was written to address exactly the needs you describe. – J_H Aug 10 '23 at 19:29

0 Answers0