python - 如何删除 'NoneType' 的字典项?

标签 python python-3.x dictionary collections

我正在制作一个程序,它获取销售人员报告,遍历它们并将它们显示在 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/

相关文章:

C# - 搜索字典的键与搜索列表中的值

python - matplotlib:在绘图中添加圆圈

python - 如何仅使用python中的云视觉api检测特定语言而忽略其他语言?

python - Numpy:索引 i < j 的一维数组的总和

c# - 词典项目顺序

python - 在循环中合并Python数组?

python - Python 基础问题 : referencing original variable inside for loop?

python - 在 Python 中,从生成器构造循环子群

python - 通过 Google Drive API 访问共享云端硬盘时出现 404 错误

python - 属性错误 : 'function' object has no attribute 'func_name' and python 3