我有一个json文件,包含大约100000行,格式如下:
{
"00-0000045": {
"birthdate": "5/18/1975",
"college": "Michigan State",
"first_name": "Flozell",
"full_name": "Flozell Adams",
"gsis_id": "00-0000045",
"gsis_name": "F.Adams",
"height": 79,
"last_name": "Adams",
"profile_id": 2499355,
"profile_url": "http://www.nfl.com/player/flozelladams/2499355/profile",
"weight": 338,
"years_pro": 13
},
"00-0000108": {
"birthdate": "12/9/1974",
"college": "Louisville",
"first_name": "David",
"full_name": "David Akers",
"gsis_id": "00-0000108",
"gsis_name": "D.Akers",
"height": 70,
"last_name": "Akers",
"number": 2,
"profile_id": 2499370,
"profile_url": "http://www.nfl.com/player/davidakers/2499370/profile",
"weight": 200,
"years_pro": 16
}
}
我正在尝试删除所有没有gsis_name
属性的项。到目前为止,我有这个python代码,但它没有删除任何值(注意:我不想覆盖原始文件)
import json
with open("players.json") as json_file:
json_data = json.load(json_file)
for x in json_data:
if 'gsis_name' not in x:
del x
print json_data
当您说
del x
时,您正在从当前作用域取消分配名称x
(在本例中是全局作用域,因为delete不在类或函数中)。你知道吗您需要从对象} 返回dict,因为主对象是关联数组/map/Javascript对象。当你迭代一个dict时,你在迭代键,所以
json_data
中删除它。^{x
是一个键(例如“00-0000108”)。这是一个bug:您想检查值是否有键gsis_name
。你知道吗dict
的文档向您展示了如何使用键从dict中删除:https://docs.python.org/3/library/stdtypes.html#mapping-types-dict但正如其他答案所说,最好用你想要的对象创建一个新的dict,而不是删除你不想要的对象。你知道吗
您正在删除x,但是x是json_数据中原始元素的一个副本;删除x实际上不会将其从绘制它的对象中删除。你知道吗
在Python中,如果要从集合中筛选出某些项,最好的办法是将所需的项复制到新集合中。你知道吗
然后将
clean_data
写入带有json.dump
的文件。你知道吗只需创建没有不需要的元素的新dict:
由于python2.7,您可以使用dict理解。你知道吗
相关问题 更多 >
编程相关推荐