Home > Blockchain >  Python: Getting value in dictionary by key and creating an array with them
Python: Getting value in dictionary by key and creating an array with them

Time:11-16

I have a dictionary like this:

{
  "0": {}, 
  "1": {}, 
  "2": {}, 
  "3": {}, 
  "4": {}, 
  "5": {}, 
  "6": {}, 
  "7": {}, 
  "8": {}, 
  "9": {}, 
  "10": {}, 
  "11": {}, 
  "12": {
    "PNR": "51313542"
  }, 
  "13": {}, 
  "14": {}, 
  "15": {
    "PNR": "13151351351"
  }, 
  "16": {
    "PNR": "13151351351"
  }, 
  "17": {
    "PNR": "13151351351"
  }, 
  "18": {
    "PNR": "13151351351"
  }, 
  "19": {
    "PNR": "13151351351"
  }, 
  "20": {
    "PNR": "13151351351"
  }, 
  "21": {
    "PNR": "13151351351"
  }, 
  "22": {
    "PNR": "13151351351"
  }, 
  "23": {
    "PNR": "13151351351"
  }, 
  "24": {
    "PNR": "13151351351"
  }
}

I wanted to get only the PNR's and creating an array with them.

I tried this for getting the PNR values (think "output" as my dict):

d_ = output.get("PNR")

But it gives None.

How can I get the PNR values no matter how many elements in my dict and create an array with them?

CodePudding user response:

You could use a list comprehension:

[v["PNR"] for v in dic.values() if "PNR" in v.keys()]

Output:

['51313542', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351']

CodePudding user response:

In case the PNRs are not all at the same level you can use recursive approach:

def get_pnr(dct):
    pnrs = []
    for k, v in dct.items():
        if k == 'PNR':
            pnrs  = [v]
        if isinstance(v, dict):
            pnrs.extend(get_pnr(v))
            
    return pnrs

a = get_pnr(d)
print(a)

Output

['51313542', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351']
  • Related