python - 如何搁置整数键?

标签 python file-io dictionary shelve persistent-storage

我想在 shelve 中存储一个整数键。但是当我尝试在 shelve 中存储整数键时,它给我一个错误

Traceback (most recent call last):
  File "./write.py", line 12, in 
    data[id] = {"Id": id, "Name": name}
  File "/usr/lib/python2.5/shelve.py", line 124, in __setitem__
    self.dict[key] = f.getvalue()
  File "/usr/lib/python2.5/bsddb/__init__.py", line 230, in __setitem__
    _DeadlockWrap(wrapF)  # self.db[key] = value
  File "/usr/lib/python2.5/bsddb/dbutils.py", line 62, in DeadlockWrap
    return function(*_args, **_kwargs)
  File "/usr/lib/python2.5/bsddb/__init__.py", line 229, in wrapF
    self.db[key] = value
TypeError: Integer keys only allowed for Recno and Queue DB's

My Code :

#!/usr/bin/python

import shelve

data = shelve.open("data.txt")

ans = 'y'
while ans == "y":
    id = input("Enter Id : ")
    name = raw_input("Enter name : ")

    data[id] = {"Id": id, "Name": name}

    ans = raw_input("Do you want to continue (y/n) ? : ")

data.close()

是我的程序有问题还是 shelve 根本不支持整数键?


编辑 1:

在程序中,我试图将 Id 和 Name 的字典存储在另一个以 Id 作为键的字典中。然后尝试将其存储在文件中。

我是否需要将 Recno 或 Queue DB 与搁置一起使用?我是初学者,事情很困惑。

如果我的问题不清楚,请告诉我。

谢谢。

最佳答案

在您的示例中,数据库中的键始终是整数,因此将它们转换为字符串应该可以正常工作,

data[str(id)] = {"Id": id, "Name": name}

我的测试代码

def shelve_some_data(filename):
    db = shelve.open(filename, flag="c")
    try:
        # note key has to be a string
        db[str(1)]    = "1 integer key that's been stringified" 
        db[str(2)]    = "2 integer key that's been stringified" 
        db[str(3)]    = "3 integer key that's been stringified" 
        db[str(10)]   = "10 integer key that's been stringified" 
    finally:
        db.close()

def whats_in(filename):
    db = shelve.open(filename, flag="r")
    for k in db:
        print("%s : %s" % (k, db[k]))
    return

filename = "spam.db"
shelve_some_data(filename)
whats_in(filename)

和输出;它像字典一样工作,因此没有排序。

2 : 2 integer key that's been stringified
10 : 10 integer key that's been stringified
1 : 1 integer key that's been stringified
3 : 3 integer key that's been stringified

关于python - 如何搁置整数键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4013452/

相关文章:

java - 确保密码不包含字典单词

java - 从 Hadoop 中的映射器发出矩阵

python - 如何使用python在多台服务器上执行命令

python - 如何将 google 分析 (GTAG) 添加到我的 python dash 应用程序?

Java - HtmlUnit - 无法将 HTML 保存到文件(在某些情况下)

python - 在 Python 中每小时将时间戳写入文件

python - 从字符串中提取整数 - 包括负整数

python - Selenium 导航后获取当前网址?

powershell - Powershell Out-File在文件顶部添加换行符-Out-File与Set-Content

c++ - 在C++中通过类内部的方法时如何正确使用 map