简体   繁体   English

如何删除具有空白值的字典键?

[英]How to delete dictionary keys that have a blank value?

Currently, I'm working on a script (3.9) that takes a.csv file, and creates a.json file out of it.目前,我正在编写一个脚本 (3.9),该脚本采用 .csv 文件,并从中创建一个 .json 文件。 The original code is as follows...原代码如下...

import csv
import json
from time import time

start = time()


def make_json(csv_path, json_path):
    data = []

    with open(csv_path, encoding='utf-8') as csvp:
        csv_reader = csv.DictReader(csvp)

        for row in csv_reader:
            data.append(row)

    with open(json_path, 'w', encoding='utf-8') as jsonp:
        jsonp.write(json.dumps(data, indent=4))


csv_path = r'elearningtest.csv'
json_path = r'elearningtest.json'

make_json(csv_path, json_path)

print(f'Time taken to run: {time() - start} seconds')

This here works as expected.这在这里按预期工作。 Here's a sample of the output...这是 output 的示例...

[
    {
        "username": "username0001",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:16",
        "completion_date": "8/28/2019 11:20",
        "score": ""
    },
    {
        "username": "username0002",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:18",
        "completion_date": "8/7/2019 17:20",
        "score": "78"
    },
    {
        "username": "username0003",

However, what I'd like is the following:但是,我想要的是以下内容:

[
    {
        "username": "username0001",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:16",
        "completion_date": "8/28/2019 11:20"
    },
    {
        "username": "username0002",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:18",
        "completion_date": "8/7/2019 17:20",
        "score": "78"
    },
    {
        "username": "username0003",

As you can see in the first entry, the value of the "score" key was "" .正如您在第一个条目中看到的, "score"键的值为"" What I'm aiming for is, if the value is "" , it simply won't include that key for that row.我的目标是,如果值为"" ,它根本不会包含该行的那个键。 This is the code I've done to accomplish this.这是我为完成此任务所做的代码。

for row in csv_reader:
    for k, v in row.items():
        if v == "":
            del row[k]
        else:
            data.append(row)  

When I run this, I get the error of RuntimeError: dictionary changed size during iteration .当我运行它时,我得到RuntimeError: dictionary changed size during iteration的错误。

I've looked all over, and have found some promising leads, but nothing that solidly helps with this.我四处寻找,找到了一些有希望的线索,但没有什么能真正帮助解决这个问题。 Any input from the community would be amazing.来自社区的任何输入都将是惊人的。

Currently, I'm working on a script (3.9) that takes a.csv file, and creates a.json file out of it.目前,我正在编写一个脚本(3.9),它需要一个.csv 文件,并从中创建一个.json 文件。 The original code is as follows...原代码如下...

import csv
import json
from time import time

start = time()


def make_json(csv_path, json_path):
    data = []

    with open(csv_path, encoding='utf-8') as csvp:
        csv_reader = csv.DictReader(csvp)

        for row in csv_reader:
            data.append(row)

    with open(json_path, 'w', encoding='utf-8') as jsonp:
        jsonp.write(json.dumps(data, indent=4))


csv_path = r'elearningtest.csv'
json_path = r'elearningtest.json'

make_json(csv_path, json_path)

print(f'Time taken to run: {time() - start} seconds')

This here works as expected.这在这里按预期工作。 Here's a sample of the output...这是 output 的样本...

[
    {
        "username": "username0001",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:16",
        "completion_date": "8/28/2019 11:20",
        "score": ""
    },
    {
        "username": "username0002",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:18",
        "completion_date": "8/7/2019 17:20",
        "score": "78"
    },
    {
        "username": "username0003",

However, what I'd like is the following:但是,我想要的是以下内容:

[
    {
        "username": "username0001",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:16",
        "completion_date": "8/28/2019 11:20"
    },
    {
        "username": "username0002",
        "course_code": "coursecode_001",
        "enrollment_date": "7/28/2015 16:18",
        "completion_date": "8/7/2019 17:20",
        "score": "78"
    },
    {
        "username": "username0003",

As you can see in the first entry, the value of the "score" key was "" .正如您在第一个条目中看到的那样, "score"键的值是"" What I'm aiming for is, if the value is "" , it simply won't include that key for that row.我的目标是,如果值为"" ,它根本不会包含该行的该键。 This is the code I've done to accomplish this.这是我为完成此操作所做的代码。

for row in csv_reader:
    for k, v in row.items():
        if v == "":
            del row[k]
        else:
            data.append(row)  

When I run this, I get the error of RuntimeError: dictionary changed size during iteration .当我运行它时,我收到RuntimeError: dictionary changed size during iteration错误。

I've looked all over, and have found some promising leads, but nothing that solidly helps with this.我已经四处寻找,并找到了一些有希望的线索,但没有任何东西对此有实质性帮助。 Any input from the community would be amazing.来自社区的任何意见都会令人惊叹。

You get that error because you're iterating over row.items() and changing the items in row at the same time.您收到该错误是因为您正在遍历row.items()并同时更改row中的项目。 There are a couple ways to get around this:有几种方法可以解决这个问题:

  1. Create a copy of row.items() before iterating over it.在迭代之前创建row.items()的副本。
for row in csv_reader:
    row_items = list(row.items())
    for k, v in row_items:
        if v == "":
            del row[k]
    # Append row to data after checking all keys
    data.append(row) 
  1. Create a new dictionary containing only those values that aren't blank instead of deleting keys from the old one:创建一个新字典,只包含那些不为空的值,而不是从旧字典中删除键:
for row in csv_reader:
    row_filtered = {k: v for k, v in row.items() if v != ""} 
    # this line can also be written as:
    # dict(item for item in row.items() if item[1] != "")    

    # Then append the filtered row
    data.append(row_filtered)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM