python - 无法使用 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
}]
我不确定为什么我不能使用删除值。我也尝试过删除,但后来我得到了一个空对象。
解决方案
您不能value
使用del
while 循环删除,如您在此处看到的那样,如果您想使用del
,您应该按其索引而不是它在 for 循环范围内采用的值删除该项目,因为正如 @MosesKoledoye 在评论中所说:
您希望
del players['Tournaments']
删除作用于字典并删除该条目,而不是 del value,它只会从范围中删除值名称。请参阅del
stmt。
当您循环并想要修改列表时,您必须创建一个副本,如您在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}]
推荐阅读
- python - 按Python中字符串中的数字对列表开头包含数字的字符串列表进行排序
- nginx - Nginx 将流量发送到错误的端口
- powershell - 来自数据源的 String 类型的值无法转换为 Real 类型
- reactjs - 反应:重置密码发送带有重置密码链接的电子邮件以重置密码
- android - 使用 ADB (Android 10) 从计算机访问外部存储的直接方式
- git - 如何通过putty中的psftp将文件夹从git repo传输到服务器?
- reactjs - 使用其他钩子的 Reactjs 钩子
- javascript - 将 JavaScript 日期格式化为“月日,年”格式
- docker - 如何从 docker-compose 文件创建 DockerFile
- hadoop - 为什么 MapReduce 分布式系统需要互斥?