![](/img/trans.png)
[英]How to convert a csv format values inside a dict to JSON format in python?
[英]Python: Cannot put json format(dict) values into a list
我試圖從 json 輸入中提取一組日期值。 當我完成F_Date
的提取時,它是正確的。
2020-05-20T00:00:00
2020-05-18T00:00:00
2020-05-15T00:00:00
2020-05-13T00:00:00
我設置了一個列表來包含這些值,所以我想使用List[0]
之類的列表索引來獲取列表中的第一個值或列表中的其他值以用於進一步的目的。 然而,它失敗了。 它給了我一列第一個字符。 如果我嘗試List[1]
,它給了我一列0
而不是2020-05-18T00:00:00
,這正是我想要的。 知道我的代碼有什么問題嗎? 我對F_Date
現在是什么類型感到困惑,它不是列表嗎?
提前致謝。
F_Date = []
for cell in json["Cells"]:
if cell["ColumnName"] == "T":
if cell["RowIndex"] + 1 > 9:
F_Date = cell["DisplayValue"]
print(F_Date[0])
output:
2
2
2
2
Json:
json = {
"SheetName": "price",
"SheetIndex": 4,
"Cells": [
{
"ColumnName": "T",
"RowName": "10",
"Address": "T10",
"ColumnIndex": 19,
"RowIndex": 9,
"Value": "2020-05-20T00:00:00",
"DisplayValue": "2020-05-20T00:00:00",
"ValueType": "Date"
},
{
"ColumnName": "U",
"RowName": "10",
"Address": "U10",
"ColumnIndex": 20,
"RowIndex": 9,
"Value": 2.75,
"DisplayValue": 2.75,
"ValueType": "Numeric"
},
{
"ColumnName": "V",
"RowName": "10",
"Address": "V10",
"ColumnIndex": 21,
"RowIndex": 9,
"Value": 2.15,
"DisplayValue": 2.15,
"ValueType": "Numeric"
},
{
"ColumnName": "T",
"RowName": "11",
"Address": "T11",
"ColumnIndex": 19,
"RowIndex": 10,
"Value": "2020-05-18T00:00:00",
"DisplayValue": "2020-05-18T00:00:00",
"ValueType": "Date"
},
{
"ColumnName": "U",
"RowName": "11",
"Address": "U11",
"ColumnIndex": 20,
"RowIndex": 10,
"Value": 2.75,
"DisplayValue": 2.75,
"ValueType": "Numeric"
},
{
"ColumnName": "V",
"RowName": "11",
"Address": "V11",
"ColumnIndex": 21,
"RowIndex": 10,
"Value": 2.15,
"DisplayValue": 2.15,
"ValueType": "Numeric"
},
{
"ColumnName": "T",
"RowName": "12",
"Address": "T12",
"ColumnIndex": 19,
"RowIndex": 11,
"Value": "2020-05-15T00:00:00",
"DisplayValue": "2020-05-15T00:00:00",
"ValueType": "Date"
},
{
"ColumnName": "U",
"RowName": "12",
"Address": "U12",
"ColumnIndex": 20,
"RowIndex": 11,
"Value": 2.75,
"DisplayValue": 2.75,
"ValueType": "Numeric"
},
{
"ColumnName": "V",
"RowName": "12",
"Address": "V12",
"ColumnIndex": 21,
"RowIndex": 11,
"Value": 2.15,
"DisplayValue": 2.15,
"ValueType": "Numeric"
},
{
"ColumnName": "T",
"RowName": "13",
"Address": "T13",
"ColumnIndex": 19,
"RowIndex": 12,
"Value": "2020-05-13T00:00:00",
"DisplayValue": "2020-05-13T00:00:00",
"ValueType": "Date"
}
]}
您需要做的就是打印 F_Date 而不是 F_Date[0] ,它只將第一個字符打印為字符串,可以解釋為字符列表,並且您正在打印索引 0。
print(F_Date)
如果您對 F_Date 是什么感到困惑,則 F_Date 是您的日期字符串,因為它是您獲得的字典中鍵的值。
F_Date = []
for cell in json["Cells"]:
if cell["ColumnName"] == "T":
if cell["RowIndex"] + 1 > 9:
F_Date = cell["DisplayValue"] # Here you set F_Date to the value
print(F_Date[0])
我想你要做的是這個
F_Date = []
for cell in json["Cells"]:
if cell["ColumnName"] == "T":
if cell["RowIndex"] + 1 > 9:
F_Date.append(cell["DisplayValue"])
print(cell["DisplayValue"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.