簡體   English   中英

如何刪除“ NoneType”的字典項?

[英]How do I delete a dict item that is a 'NoneType'?

我正在制作一個程序,用於接收salesforce報告,對其進行迭代,然后將其顯示在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)

您不應在僅包含None作為值的較大字典中放入任何內容。 我的原始代碼不正確,這是TemporalWolf建議的解決方案。

if(None not in temp):
    reports.update(temp)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM