我试图在json中输出一个键等于一个特定的值


l = []
with open("acw_user_data.csv", 'r') as data_file:
reader = csv.reader(data_file)
headers = next(reader)

for reader_row in reader:

d = {}
d[headers[11]] = str(reader_row[11])
d[headers[13]] = str(reader_row[13])
d[headers[3]] = int(reader_row[3])
d[headers[18]] = str(reader_row[18])
d[headers[16]] = bool(reader_row[16])
import json
with open("assignemt", 'w', encoding='utf-8') as jsonf: 
jsonString = json.dumps(l, indent=4)
jsonf.write(jsonString)
结果:

{
"First Name": "Jodie",
"Last Name": "O'Brien",
"Age (Years)": 57,
"Sex": "Female",
"Retired": true
},
{
"First Name": "Leke",
"Last Name": "Dan",
"Age (Years)": 57,
"Sex": "male",
"Retired": false
},
{
"First Name": "joe",
"Last Name": "frank",
"Age (Years)": 22,
"Sex": "Female",
"Retired": true
}

我有这个Json转储创建从一个csv文件。我只需要Age(Years) = 22的Json转储

我想得到相同的结果,但只适用于年龄为22或退休为真

我该怎么做?

使用列表推导式:

22岁:

with open("assignemt", 'w', encoding='utf-8') as jsonf: 
json.dump([d for d in l if d['Age (Years)'] == 22], jsonf)

年龄22岁或已退休:

with open("assignemt", 'w', encoding='utf-8') as jsonf: 
json.dump([d for d in l if d['Age (Years)'] == 22 or d['Retired']], jsonf)

相关内容

  • 没有找到相关文章

最新更新