JSON file I have has following data:
{
"P1":{
"L1":{
"crn":"1"
},
"L2":{
"crn":"100"
}
},
"P2":{
"L3":{
"crn":"xx"
},
"L4":{
"crn":"xxxx"
}
}
}
How do I get [L1,L2,L3,L4] efficiently?
I can load the data and loop over dict.values().
Is there any better, efficient way?
>Solution :
You can use a list comprehension to extract the room numbers, then use itertools.chain.from_iterable to flatten everything into a one-dimensional list:
import json
from itertools import chain
with open('input.json') as input_file:
data = json.load(input_file)
# Prints ['L1', 'L2', 'L3', 'L4']
print(list(chain.from_iterable(value.keys() for value in data.values())))