'Flatten/merge dictionary with nested dictionaries

I've got the following dictionary example:

z1 = {
  "ZH": {
    "hosts": {
      "zhsap001.domain.com": {
        "active": "y",
        "ip": "11.111.11.10",
        "zone": "North"
      },
      "zhsap002.domain.com": {
        "active": "y",
        "ip": "11.111.11.11",
        "zone": "North"
      }
    }
  },
  "BE": {
    "hosts": {
      "besap001.domain.com": {
        "active": "y",
        "ip": "22.222.2.20",
        "zone": "Center"
      },
      "besap002.domain.com": {
        "active": "y",
        "ip": "10.214.4.58",
        "zone": "Center"
      }
    }
  }
}

And I'd like to "flatten" it to:

z2 = {
   "zhsap001.domain.com": {
      "active": "y",
      "ip": "11.111.11.10",
      "zone": "North"
   },
   "zhsap002.domain.com": {
      "active": "y",
      "ip": "11.111.11.11",
      "zone": "North"
   },
   "besap001.domain.com": {
      "active": "y",
      "ip": "22.222.2.20",
      "zone": "Center"
   },
   "besap002.domain.com": {
      "active": "y",
      "ip": "10.214.4.58",
      "zone": "Center"
   }
}

I can create z2 from z1 by running:

z2 = {}
for a in z1.values():
    for b in a.values():
        for (c,d) in b.items():
            z2.update({c:d})

But I would like to achieve the same in a more Pythonized manner using a comprehension expression or lambda function.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source