python searching through dict that contain list of nested dict

Viewed 32

I am looking to pull all the "symbol" from a Dict that looks like this:

file_data = json.load(f)

{
  "symbolsList" : [ {
    "symbol" : "SPY",
    "name" : "SPDR S&P 500",
    "price" : 261.56,
    "exchange" : "NYSE Arca"
  }, {
    "symbol" : "CMCSA",
    "name" : "Comcast Corporation Class A Common Stock",
    "price" : 35.49,
    "exchange" : "Nasdaq Global Select"
  }, {
    "symbol" : "KMI",
    "name" : "Kinder Morgan Inc.",
    "price" : 13.27,
    "exchange" : "New York Stock Exchange"
  }
}

after looking up I found a way to access certain symbol. but I would like to get all the symbol in a form of list or dict doesn't really matter to me. this is what I got:

print([next(item for item in file_data["symbolsList"] if item["symbol"] == "SPY")])

I know that the problem is with the next function I just don't know how to get all the symbols

1 Answers

you can use a list comprehension:

[e['symbol'] for e in d['symbolsList']]

output:

['SPY', 'CMCSA', 'KMI']

the same thing using a for loop:

result = []
for e in d['symbolsList']
    result.append(e['symbol'])
Related