I have list of dictionaries that looks like this:
planets = [
{ "name": "Mercury", "moonCount": 0 },
{ "name": "Venus", "moonCount": 0 },
{ "name": "Earth", "moonCount": 1 },
{
"name": "Mars",
"moonCount": 2
},
{
"name": "Jupiter",
"moonCount": 67
},
{
"name": "Saturn",
"moonCount": 62
},
{
"name": "Uranus",
"moonCount": 27
},
{
"name": "Neptune",
"moonCount": 13
},
{
"name": "Pluto",
"moonCount": 4
}
]
I am trying to get the list of all planets which do not have moons. I can do this very simply if turn this into panda dataframe like this:
import pandas as pd
df = pd.json_normalize(planets)
no_moon_planets = df.loc[df['moonCount']==0, 'name']
no_moon_planets = no_moon_planets.tolist()
no_moon_planets
But I need to do this without creating panda dataframe. So basically looking for solution where I can extract the list of the planet directly from list of dictionaries where the number of the moons iz zero.
Any help is appreciated.
CodePudding user response:
Do the following :
Planets_without_moon = [i['name'] for i in planets if i['moonCount']==0]
CodePudding user response:
You can simply do it with list comprehension:
zero_moon = [dic for dic in planets if dic["moonCount"]==0]
if you just want the name of the planet:
zero_moon = [dic["name"] for dic in planets if dic["moonCount"]==0]