I am storing stock data in a JSON file that looks like this:
{
"06/01/2021 18:41:02": {
"NASDAQ-BYND": {
"Sell": "6",
"Neutral": "9",
"Buy": "11"
},
"NYSE-CCL": {
"Sell": "3",
"Neutral": "8",
"Buy": "15"
},
"NASDAQ-NVDA": {
"Sell": "2",
"Neutral": "8",
"Buy": "16"
},
"NASDAQ-TQQQ": {
"Sell": "2",
"Neutral": "8",
"Buy": "16"
}
}
}
I am trying to sort the dictionary by the 'Buy' value so that my result looks like this:
{
"NASDAQ-NVDA": {
"Sell": "2",
"Neutral": "8",
"Buy": "16"
},
"NASDAQ-TQQQ": {
"Sell": "2",
"Neutral": "8",
"Buy": "16"
},
"NYSE-CCL": {
"Sell": "3",
"Neutral": "8",
"Buy": "15"
},
"NASDAQ-BYND": {
"Sell": "6",
"Neutral": "9",
"Buy": "11"
}
}
My code currently looks like this:
with open("/dayData.json", 'r') as day:
data = json.load(day)
keys = list(data)
print(sorted(data[keys[len(keys)-1]].items(), key = lambda x: x[1]['Buy'])
The reason I store the initial keys in the keys
variable is because the original JSON file is quite large and I only want to get the data from the last dated entry. Calling list(data)
only returns the initial parent keys which are all of the dates.
The result of running the code above:
{
"NASDAQ-BYND": { "Sell": "6", "Neutral": "9", "Buy": "11" },
"NYSE-CCL": { "Sell": "3", "Neutral": "8", "Buy": "15" },
"NASDAQ-NVDA": { "Sell": "2", "Neutral": "8", "Buy": "16" },
"NASDAQ-TQQQ": { "Sell": "2", "Neutral": "8", "Buy": "16" },
"NYSE-AMC": { "Sell": "1", "Neutral": "9", "Buy": "16" },
"NASDAQ-AMZN": { "Sell": "14", "Neutral": "10", "Buy": "2" },
"NASDAQ-AAPL": { "Sell": "13", "Neutral": "10", "Buy": "3" },
"NASDAQ-COIN": { "Sell": "7", "Neutral": "7", "Buy": "3" },
"NASDAQ-MARA": { "Sell": "10", "Neutral": "9", "Buy": "7" },
"NASDAQ-TSLA": { "Sell": "9", "Neutral": "8", "Buy": "9" }
}
What am I doing wrong or need to know?