[英]How to loop through a JSON file using Python with nested lists and dictionaries
[英]how to filter nested dictionaries of a json file, in Python
我有一個 JSON 文件,其中的數據如下所示:
樣本數據:(實際數據會有多年的匯率)
原來的:
{
"rates":{
"2018-01-22":{
"BGN":1.9558,
"TRY":4.6552,
"CNY":7.8374,
"NOK":9.6223,
"NZD":1.6758
},
"2018-01-09":{
"BGN":1.9558,
"TRY":4.4843,
"CNY":7.7865,
"NOK":9.6715,
"NZD":1.6601
}
},
"start_at":"2018-01-01",
"base":"EUR",
"end_at":"2018-02-01"
}
預期的:
{
"rates":{
"2018-01-22":{
"BGN":1.9558,
"CNY":7.8374,
"NZD":1.6758
},
"2018-01-09":{
"BGN":1.9558,
"CNY":7.7865,
"NZD":1.6601
}
},
"start_at":"2018-01-01",
"base":"EUR",
"end_at":"2018-02-01"
}
我主要需要幫助:
就此獲得一些建議也會非常有幫助:
您可以通過列表/字典理解來解決它。 但是有不止一種方法可以做到這一點。 這是列表/字典理解的示例。 在變量選擇中,您可以放置所有想要保留的貨幣:
data = {'rates': {'2018-01-22': {'BGN': 1.9558, 'TRY': 4.6552,
'CNY': 7.8374, 'NOK': 9.6223, 'NZD': 1.6758}, '2018-01-09':
{'BGN': 1.9558, 'TRY': 4.4843, 'CNY': 7.7865, 'NOK': 9.6715,
'NZD': 1.6601}}, 'start_at': '2018-01-01', 'base': 'EUR',
'end_at': '2018-02-01'}
choice = ("BGN", "CNY", "NZD")
filtered = {date: {x: data.get("rates").get(date).get(x) for x in data.get("rates").get(date) if x in choice} for date in data.get("rates")}
data["rates"] = filtered
print(data)
關於數據庫:對於如下列,我可能會使用 go。 但這也取決於數據的使用方式。
日期| 貨幣 1 |... | 貨幣N | 根據
然后您可以輕松地按日期或貨幣進行排序和過濾,這很可能是您大多數時候想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.