我正在制作一个程序,它获取销售人员报告,遍历它们并将它们显示在 Flask 应用程序中。
from flask import Flask
from flask import render_template
import csv
import collections
app = Flask(__name__)
# odict_keys(['Edit', 'Activity ID', 'Assigned', 'Subject', 'Last Modified Date', 'Date', 'Priority'
# , 'Status', 'Company / Account', 'Created By', 'Activity Type', 'Comments'])
@app.route('/')
def hello_world():
reports = {}
with open('./reports/report040717.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
for row in reader:
temp = {row['Activity ID']: {'subject': row['Subject'], 'due_date': row['Date'], 'last_modified': row['Last Modified Date'], 'status': row['Status'],
'company': row['Company / Account'], 'type': row['Activity Type'], 'comments': row['Comments']}}
reports.update(temp)
reports = collections.OrderedDict(reversed(list(reports.items())))
for k, v in reports.items():
print(k, v)
return render_template('home.html', reports=reports)
if __name__ == '__main__':
app.run()
我将读取的所有行存储到一个字典中,然后将该字典推送到另一个以 ID 作为键的字典中。
问题是我一直得到一个空字典,但我不知道如何删除它。
这就是它在调用渲染之前打印 k ,v 值时的显示方式
None {'subject': None, 'due_date': None, 'last_modified': None, 'status': None, 'company': None, 'type': None, 'comments': None}
这就是所有其他人出现的方式
00TF000003Ti9iE {'subject': 'some text', 'due_date': '4/18/2017', 'last_modified': '8/23/2016', 'status': 'Not Started', 'company': 'some text', 'type': 'some text', 'comments': 'some text'}
关于如何删除报告字典中的 None 条目有什么建议吗?
最佳答案
我会想象您从 CSV 文件中读取空行。您可以执行以下操作,以便根本不会将这些空行加载到字典中:
if row['Activity ID'] and row['Subject']:
# row will only be added if the values above aren't None
temp = {row['Activity ID']: {'subject': row['Subject'], 'due_date': row['Date'], 'last_modified': row['Last Modified Date'], 'status': row['Status'],
'company': row['Company / Account'], 'type': row['Activity Type'], 'comments': row['Comments']}}
reports.update(temp)
关于python - 如何删除 'NoneType' 的字典项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283348/