2

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?

2
  • What should happen if there is no PNR key in specific sub-dict? Commented Nov 15, 2021 at 20:51
  • Do you mean a list? Commented Nov 15, 2021 at 21:18

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

Comments

2

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']

1 Comment

pnrs += [v] should be pnrs.append(v)...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.