You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本JSON去重时报TypeError:列表索引需为整数/切片而非字符串

问题:基于userid去除两个JSON文件重复项时的TypeError问题

我编写了一段Python脚本,想要通过userid去除两个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"
    }
}

之后我按照John的建议修改了脚本,但仍未解决问题,修改后的脚本如下:

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.values():
   # print(item) # print scanned results on CMD
    #if item['userid'] not in [x['userid'] for x in source]:
    #if item['userid'] not in [x['userid'] for x in source]:
    if target[item]['userid'] not in [source[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)

恳请各位提供解决方案。


内容的提问来源于stack exchange,提问作者James Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 01:15:19