我已运行以下 Python 脚本来根据用户 ID 删除两个 json 文件之间的重复项:
import json
with open("target_user.json", "r", encoding='utf-8') as f1:
target = json.load(f1)
with open("source_user.json", "r", encoding='utf-8') as f2:
source = json.load(f2)
target2 = []
for item in target:
if item['userid'] not in [x['userid'] for x in source]:
target2.append(item)
with open('target_user2.json', 'w', encoding='utf-8') as nf:
json.dump(target2, nf, indent=4)
它会产生错误:
TypeError: list indices must be integers or slices, not str
从这一行:
if item['userid'] not in [x['userid'] for x in source]:
我已尝试以下方法,但没有解决:
if dict([item]['userid']) not in [dict[x]['userid'] for x in source]:
这是我的 json 文件的示例:
{
"567897068": {
"userid": "567897068",
"status": "UserStatus.OFFLINE",
"name": "btb appeal",
"bot": false,
"username": "None"
},
"5994781619": {
"userid": "5994781619",
"status": "UserStatus.OFFLINE",
"name": "Ahh",
"bot": false,
"username": "hourng999"
},
"1873973169": {
"userid": "1873973169",
"status": "UserStatus.RECENTLY",
"name": "Chanthy",
"bot": false,
"username": "Alis_Thy"
}
}
如有任何帮助,我们将不胜感激。
target
是一本字典。
当您使用
for item in target
迭代字典时,它会返回字典的 keys,它们是字符串。
因此,在第一次循环迭代中,`item