[英]Iterate through multi level json/dictionaries in Python 3
我正在從 api 獲取數據
data = json.loads(api_response.content)
返回
{
'NKE': {
'quote': {
'symbol': 'NKE',
'companyName': 'NIKE, Inc.',
'primaryExchange': 'New York Stock Exchange',
'calculationPrice': 'close',
'open': 101.14,
'openTime': 1578321000670,
'close': 101.83,
'closeTime': 1578344409251,
'high': 101.84,
'low': 100.869,
'latestPrice': 101.83,
'latestSource': 'Close',
'latestTime': 'January 6, 2020',
'latestUpdate': 1578344409251,
'latestVolume': 4608458,
'iexRealtimePrice': 0,
'iexRealtimeSize': 0,
'iexLastUpdated': 0,
'delayedPrice': 101.83,
'delayedPriceTime': 1578346947002,
'extendedPrice': 101.99,
'extendedChange': 0.16,
'extendedChangePercent': 0.00157,
'extendedPriceTime': 1578400716493,
'previousClose': 101.92,
'previousVolume': 4542003,
'change': -0.09,
'changePercent': -0.00088,
'volume': 0,
'iexMarketPercent': None,
'iexVolume': 0,
'avgTotalVolume': 5776147,
'iexBidPrice': 0,
'iexBidSize': 0,
'iexAskPrice': 0,
'iexAskSize': 0,
'marketCap': 158959684900,
'peRatio': 34.88,
'week52High': 102.21,
'week52Low': 74.3,
'ytdChange': -0.0045,
'lastTradeTime': 1578344409241,
'isUSMarketOpen': False
}
},
'UAA': {
'quote': {
'symbol': 'UAA',
'companyName': 'Under Armour, Inc.',
'primaryExchange': 'New York Stock Exchange',
'calculationPrice': 'close',
'open': 21.51,
'openTime': 1578321000404,
'close': 20.44,
'closeTime': 1578344686271,
'high': 21.53,
'low': 20.35,
'latestPrice': 20.44,
'latestSource': 'Close',
'latestTime': 'January 6, 2020',
'latestUpdate': 1578344686271,
'latestVolume': 11132892,
'iexRealtimePrice': 0,
'iexRealtimeSize': 0,
'iexLastUpdated': 0,
'delayedPrice': 20.49,
'delayedPriceTime': 1578347272279,
'extendedPrice': 0,
'extendedChange': None,
'extendedChangePercent': None,
'extendedPriceTime': 1578356330039,
'previousClose': 21.85,
'previousVolume': 4596587,
'change': -1.41,
'changePercent': -0.06453,
'volume': 0,
'iexMarketPercent': None,
'iexVolume': 0,
'avgTotalVolume': 4329339,
'iexBidPrice': 0,
'iexBidSize': 0,
'iexAskPrice': 0,
'iexAskSize': 0,
'marketCap': 9230009040,
'peRatio': 82.55,
'week52High': 27.72,
'week52Low': 16.74,
'ytdChange': -0.126054,
'lastTradeTime': 1578344399983,
'isUSMarketOpen': False
}
},
我的目標是訪問第三級也是最后一級的元素,如符號、公司名稱和最新價格,並將其添加到數據庫中
dic_data = {
"symbol": data['symbol'] ,
"latestPrice": data['latestPrice'] ,
"companyName": data['companyName'],
"week52High": data['week52High'] ,
"week52Low": data['week52Low'] ,
"ytdChange": data['ytdChange'] ,
"latestTime": data['latestTime'],
"changePercent": data['changePercent'] ,
}
)
如何遍歷數據並訪問字典的最后一級?
要循環遍歷所有quote
字典,請執行以下操作:
for key in data:
data_quote = data[key]['quote']
for quote_key in data_quote:
# Do your stuff with data_quote[quote_key]
嘗試這個:
li = []
for i in data:
for j in data[i]:
li.append({'symbol': data[i][j]['symbol'], "latestPrice": data[i][j]['latestPrice']})
print(li)
這將為您提供輸出:
output = [
{
"symbol": data[company]['quote']['symbol'],
"latestPrice": data[company]['quote']['latestPrice'],
"companyName": data[company]['quote']['companyName'],
"week52High": data[company]['quote']['week52High'],
"week52Low": data[company]['quote']['week52Low'],
"ytdChange": data[company]['quote']['ytdChange'],
"latestTime": data[company]['quote']['latestTime'],
"changePercent": data[company]['quote']['changePercent'],
} for company in data
]
已經發布了很好的答案。 我只是發布一個遞歸方法。 這只是為了帶出可以解決的各種方法。
請注意對遞歸方法的警告無處不在。 但是,如果您事先不知道需要多少個 for 循環來解決問題,那么遞歸是一個不錯的方法
我的代碼如下。 我假設 data 是您擁有的嵌套字典的名稱。 ReturnedDict是您最終想要的字典的名稱。
from collections import defaultdict
LookUpList = ['symbol' , 'latestPrice','companyName', 'week52High' , 'week52Low' , 'ytdChange' ,'latestTime', 'changePercent']
ReturnedDict = defaultdict(list)
def ReachALevelAndGrabValue(DictionaryToAssess):
for everyKey in DictionaryToAssess:
if isinstance(DictionaryToAssess[everyKey], dict):
ReachALevelAndGrabValue(DictionaryToAssess[everyKey])
else:
if everyKey in LookUpList:
ReturnedDict[everyKey].append(DictionaryToAssess[everyKey])
ReachALevelAndGrabValue(data)
print(ReturnedDict)
這給了我如下的打印輸出。
defaultdict(<class 'list'>, {'symbol': ['NKE', 'UAA'], 'companyName': ['NIKE, Inc.', 'Under Armour, Inc.'], 'latestPrice': [101.83, 20.44], 'latestTime': ['January 6, 2020', 'January 6, 2020'], 'changePercent': [-0.00088, -0.06453], 'week52High': [102.21, 27.72], 'week52Low': [74.3, 16.74], 'ytdChange': [-0.0045, -0.126054]})
這是你想要的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.