为什么我在Python的字典和列表中得到重复的键?

  • 本文关键字:列表 字典 Python python
  • 更新时间 :
  • 英文 :


我的问题是,我有时会在字典或列表中得到重复的键(事先检查项是否存在)。我没办法以任何一致性复制它。

目前我正在保存一份用户访问我的电报机器人的列表,例如:

async def myfunction()
..........
users={}
if os.access("userlist.json", os.R_OK):
with open ('userlist.json') as f:
users=json.load(f)
currentuser=[str(update.message.from_user.id),update.message.from_user.username,update.message.from_user.first_name,update.message.from_user.last_name,False,1]
if currentuser[0] in users:
currentuser[5]+=users[currentuser[0]][5] #counting how many messages the user sent to the bot
users[currentuser[0]]=currentuser
with open ('userlist.json','w') as f:
json.dump(users,f)
........

下面是一个来自服务器的json转储字典的例子:

{"1033556742": [1033556742, "CatchingStars", "Starcatcher", null, false, 1], "1033556742": [1033556742, "CatchingStars", "Starcatcher", null, false, 1]}

我也有一个类似的代码补丁,我以类似的方式将项目添加到列表中:我从json加载列表,我检查项目是否在列表中:

if item in list: print ('ok')
else: 
list.append(item)
with ('mylist.json','w') as f:
json.dump(list,f)

,偶有重复项。

我可以解释你的重复密钥。这是json模块的怪癖。

问题是JSON不支持数字键。键必须总是字符串。您正在加载JSON,其中有一个字符串键,然后添加另一个具有与整数相同值的条目。Python允许将其作为两个单独的键,但JSON模块将其转换为字符串。注意:

Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> x = {123:'abc', "123":'abc'}
>>> x
{123: 'abc', '123': 'abc'}
>>> json.dumps(x)
'{"123": "abc", "123": "abc"}'
>>> 

最新更新