我想比較 JSON 檔案中鍵的值,通過查看檔案中是否存在當前日期來查看我是否記錄了今天日期的資料,因此我不記錄當天的資料。但是即使日期存在,這種方法似乎也回傳 False 。
def removeJsonDupes(JSONcompleteFilePath, date):
with open(JSONcompleteFilePath, "r") as file:
dictionary = json.load(file)
if dictionary.get("date") is str(date):
dateRecorded = True
print(date, "is in the dict")
else:
dateRecorded = False
print(date, "is not in the dict")
return dateRecorded
JSON 內容:
{
"prices": [
{
"date": "07/12/21",
"prices": [
"2.49",
"1.61"
]
}
]
}
uj5u.com熱心網友回復:
基于@TheFlyingObject 的回答,date您嘗試檢索的密鑰嵌套在字典中。
為了訪問它,您需要首先獲取存盤它的鍵(即prices保存串列的鍵),然后遍歷該串列中的物件。
例如:
for i in dictionary['prices']:
if i['date'] is str(date):
print(date, 'is in the dict')
return True
# we finished going over the list inside the prices key, and didn't find the date we were looking for
print(date, 'is not in the dict')
return False
uj5u.com熱心網友回復:
的dictionary.get()并查找鍵你只有prices關鍵。關鍵date在于鍵的值prices。
uj5u.com熱心網友回復:
更改功能如下
def removeJsonDupes(JSONcompleteFilePath, date):
with open(JSONcompleteFilePath, "r") as file:
dictionary = json.load(file)
if dictionary.get('prices')[0]['date'] is str(date): # condition changed
dateRecorded = True
print(date, "is in the dict")
else:
dateRecorded = False
print(date, "is not in the dict")
return dateRecorded
將給出以下結果
dictionary = {
"prices": [
{
"date": "07/12/21",
"prices": [
"2.49",
"1.61"
]
}
]
}
removeJsonDupes(dictionary, "07/12/21")
# 07/12/21 is in the dict
removeJsonDupes(dictionary, "07/12/22")
# 07/12/22 is not in the dict
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377180.html
上一篇:熊貓:用字典替換不適用于句子串
