Home > OS >  python list comprehension crate multiple dictionary
python list comprehension crate multiple dictionary

Time:07-30

In python list comprehension I can create a single flattened dictionary easily but I want to create a nested dictionary with some subkeys.

What I am doing:

import json

jsn = """
{
  "availResponse": {
    "roomStayInfos": [
      {
        "rateCodeID": 400166,
        "amount": 9000,
        "depositAmount": 0,
        "baseAmt": 9000
      },
      {
        "rateCodeID": 402451,
        "amount": 96000,
        "depositAmount": 0,
        "baseAmt": 96000
      },
      {
        "rateCodeID": 400164,
        "amount": 9000,
        "depositAmount": 0,
        "baseAmt": 9000
      },
      {
        "rateCodeID": 402598,
        "amount": 5100,
        "depositAmount": 0,
        "baseAmt": 9000
      }
    ]
  }
}
"""

availability = json.loads(jsn, strict=False)
depositAmounts = {
        str(rs["rateCodeID"]): rs["depositAmount"]
        for rs in availability["availResponse"]["roomStayInfos"]
}

print(depositAmounts)

This is working fine but I want to make 2 more subkeys for that dictionary but I don't want to do separate iterations. Like:

amount = {
            str(rs["rateCodeID"]): rs["amount"]
            for rs in availability["availResponse"]["roomStayInfos"]
    }
baseAmt = {
            str(rs["rateCodeID"]): rs["baseAmt"]
            for rs in availability["availResponse"]["roomStayInfos"]
    }

What I can do: It is working as expected

diposite_amount_baseamount = {
"depositAmounts" : {},
"amount" : {},
"baseAmt" : {},
}
for rs in availability["availResponse"]["roomStayInfos"]:
    diposite_amount_baseamount["depositAmounts"].update({ str(rs["rateCodeID"]): rs["depositAmount"]})
    diposite_amount_baseamount["amount"].update({ str(rs["rateCodeID"]): rs["amount"]})
    diposite_amount_baseamount["baseAmt"].update({ str(rs["rateCodeID"]): rs["baseAmt"]})

print(diposite_amount_baseamount)

Expected Output

{
  "depositAmounts": {
    "400164": 0,
    "400166": 0,
    "402451": 0,
    "402598": 0
  },
  "amount": {
    "400164": 9000,
    "400166": 9000,
    "402451": 96000,
    "402598": 5100
  },
  "baseAmt": {
    "400164": 9000,
    "400166": 9000,
    "402451": 96000,
    "402598": 9000
  }
}

The above code is working fine but I want to know the syntax to create a nested dictionary generation process while using list comprehension, I assume it is only the syntax that I am looking for now nothing else. Two reasons to ask this question, (1) list comprehension seems less code. (2) I don't want to iterate multiple times for the same list element to build the nested dictionary.

CodePudding user response:

You would necessarily have to map things a little before processing, i.e.

map_ = [
    ("depositAmounts", "rateCodeID", "depositAmount"),
    #              ^            
  • Related