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

Python字典键存在却无法识别及重复键被覆盖问题求助

Python字典重复Key与Key查找失败问题排查与解决

问题概述

  • 字典中明明存在指定Key,却无法通过查找匹配到
  • 字典定义时出现重复Key,后续Key会直接覆盖之前的对应值

相关代码与输出

字典定义代码

profile_account={"3286686": {"password": "hjhljjlllllllllll", "username": "oubbbbb", "trader_code":
0, "bot_code": 0, "addres_wallet": "", "state_user": "-", "expire_Data": "", 
"telegram_username": "future0bot", "Register": True, "trader": False, "is_bot": False}, 
"3286686": {"password": "ryyyyyyyyyy", "username": "urmuyr", "trader_code": 0, 
"bot_code": 0, "addres_wallet": "", "state_user": "-", "expire_Data": "", 
"telegram_username": "future0bot", "Register": True, "trader": False, "is_bot": False}}

打印操作代码

print(profile_account)
print(message.from_id,[*profile_account])
print(message.from_id not in profile_account)

打印输出结果

{'328660186': {'password': 'ryyyyyyyyyy', 'username': 'urmuyr', 'trader_code': 0,
'bot_code': 0, 'addres_wallet': '', 'state_user': '-', 'expire_Data': '', 
'telegram_username': 'future0bot', 'Register': True, 'trader': False, 'is_bot': False}}
328660186 ['328660186']
True

序列化与反序列化代码

json.dump(profile_account, open('profile_account.json', 'w'))
profile_account = json.load(open('profile_account.json'))

问题原因分析

  1. 重复Key被覆盖:Python标准字典(包括3.7+的有序字典)不支持重复Key,当定义时出现相同Key,后声明的键值对会直接覆盖之前的。你定义的字典中两次使用"3286686"作为Key,最终字典仅保留最后一个Key对应的value。
  2. Key查找失败:
    • 类型不匹配:message.from_id是整数类型,而字典的Key是字符串类型,整数与字符串不会被判定为相等,导致查找失败。
    • 数值不一致:输出中字典的Key是"328660186",与你定义的"3286686"存在数值差异,属于笔误或数据存储错误。

解决方案

1. 处理重复Key问题

  • 如果需要为同一标识存储多条数据,改用列表嵌套字典的结构,示例:
    profile_account = [
        {"user_id": "3286686", "password": "hjhljjlllllllllll", "username": "oubbbbb", "trader_code": 0, "bot_code": 0, "addres_wallet": "", "state_user": "-", "expire_Data": "", "telegram_username": "future0bot", "Register": True, "trader": False, "is_bot": False},
        {"user_id": "3286686", "password": "ryyyyyyyyyy", "username": "urmuyr", "trader_code": 0, "bot_code": 0, "addres_wallet": "", "state_user": "-", "expire_Data": "", "telegram_username": "future0bot", "Register": True, "trader": False, "is_bot": False}
    ]
    
  • 如果用户ID应唯一,检查数据生成逻辑,避免产生重复ID。

2. 解决Key查找失败问题

  • 统一类型:将message.from_id转换为字符串后再进行查找,示例:
    user_id_str = str(message.from_id)
    print(user_id_str not in profile_account)
    
  • 核对数值:确认字典中的Key与message.from_id的数值完全一致,修正笔误。

3. 优化序列化反序列化操作

  • 使用with语句管理文件,避免资源泄漏:
    import json
    
    # 序列化
    with open('profile_account.json', 'w', encoding='utf-8') as f:
        json.dump(profile_account, f, ensure_ascii=False, indent=4)
    
    # 反序列化
    with open('profile_account.json', 'r', encoding='utf-8') as f:
        profile_account = json.load(f)
    
  • JSON序列化后字典Key会保持字符串类型,查找时需使用字符串类型的Key。

内容的提问来源于stack exchange,提问作者حسین سلطانی

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:55:19