【发布时间】:2014-06-14 23:40:08
【问题描述】:
我有一个 JSON 对象,其中包含一些随机重复的属性。我想根据"word" index 删除那些重复的,只保留第一次出现,如示例所示:
{ "word" : "Apple", "meaning" : "First meaning" },
{ "word" : "Ball", "meaning" : " \u090f\u0909\u091f\u093e" },
{ "word" : "Cat", "meaning" : " \u090f\u0909\u091f\u093e" },
{ "word" : "Apple", "meaning" : "Repeated, but has another meaning" },
{ "word" : "Doll", "meaning" : " \u090f\u0909\u091f\u093e" },
我是一名 Python 初学者,目前无法领先于这个解决方案:
#!/usr/bin
import json
source="/var/www/dictionary/repeated.json"
destination="/var/www/dictionary/corrected.json"
def remove_redundant():
with open(source, "r") as src:
src_object = json.load(src)
for i in xrange(len(src_object)):
escape = 1
for j in xrange(len(src_object)):
if src_object[j]["word"] == src_object[i]["word"]:
# leave the first occurance
if escape == 1:
escape = 2
continue
else:
src_object.pop(j)
# open(destination, "w+").write(json.dumps(src_object, sort_keys=True, indent=4, separators=(',', ': ')))
src.close()
remove_redundant()
我不断收到的错误是IndexError: list index out of range,因为 len 不断变化。感谢您的帮助。
【问题讨论】:
-
这是一个字典列表吗?
标签: python