首页 > 解决方案 > 无法使用 del 方法从字典列表中删除字典

问题描述

我正在尝试删除每个点值为 0 的字典,但是当我运行此代码时,该对象仍然存在。这里有特殊情况为什么它不会删除?

import json
import numpy as np
import pandas as pd
from itertools import groupby

# using json open the player objects file and set it equal to data
with open('Combined_Players_DK.json') as json_file:
    player_data = json.load(json_file)

for player in player_data:
   for points in player['Tournaments']:
       player['Average'] = round(sum(float(tourny['Points']) for tourny in player['Tournaments']) / len(player['Tournaments']),2)

for players in player_data:
    for value in players['Tournaments']:
        if value['Points'] == 0:
            del value

with open('PGA_Player_Objects_With_Average.json', 'w') as my_file:
    json.dump(player_data, my_file)

这是JSON

[
  {
    "Name": "Dustin Johnson",
    "Tournaments": [
      {
        "Date": "2020-06-25",
        "Points": 133.5
      },
      {
        "Date": "2020-06-18",
        "Points": 101
      },
      {
        "Date": "2020-06-11",
        "Points": 25
      },
      {
        "Date": "2020-02-20",
        "Points": 60
      },
      {
        "Date": "2020-02-13",
        "Points": 89.5
      },
      {
        "Date": "2020-02-06",
        "Points": 69.5
      },
      {
        "Date": "2020-01-02",
        "Points": 91
      },
      {
        "Date": "2019-12-04",
        "Points": 0
      }
    ],
    "Average": 71.19
  }]

我不确定为什么我不能使用删除值。我也尝试过删除,但后来我得到了一个空对象。

标签: pythondictionary

解决方案


您不能value使用delwhile 循环删除,如您在此处看到的那样,如果您想使用del,您应该按其索引而不是它在 for 循环范围内采用的值删除该项目,因为正如 @MosesKoledoye 在评论中所说:

您希望del players['Tournaments']删除作用于字典并删除该条目,而不是 del value,它只会从范围中删除值名称。请参阅delstmt。

当您循环并想要修改列表时,您必须创建一个副本,如您在docs中所见。我建议您查看上面的链接,以查看在循环时删除元素的其他方法。尝试这个:

for players in player_data:
    for i in range(len(players['Tournaments'])):
        if players['Tournaments'][i]['Points'] == 0:
            del players['Tournaments'][i]

我更喜欢使用更好的字典理解,所以你也可以试试这个:

player_data[0]['Tournaments']=[dct for dct in player_data[0]['Tournaments'] if dct['Points']!=0]
print(data)

输出:

[{'Name': 'Dustin Johnson', 'Tournaments': [{'Date': '2020-06-25', 'Points': 133.5}, {'Date': '2020-06-18', 'Points': 101}, {'Date': '2020-06-11', 'Points': 25}, {'Date': '2020-02-20', 'Points': 60}, {'Date': '2020-02-13', 'Points': 89.5}, {'Date': '2020-02-06', 'Points': 69.5}, {'Date': '2020-01-02', 'Points': 91}], 'Average': 71.19}]

推荐阅读