PYTHON3 (不是 PYTHON2 ) TypeError:不会隐式将 Unicode 转换为字节;使用.encode()

vin*_*t75 4 unicode byte encode transactions python-3.5

我有这个函数可以与 python2 完美配合

 def writeCache(env, cache):
        with env.begin(write=True) as txn:
            for k, v in cache.items():
                txn.put(k, v)
Run Code Online (Sandbox Code Playgroud)

但是,当我执行它时,python3.5.2它会返回以下错误:

txn.put(k, v)
TypeError: Won't implicitly convert Unicode to bytes; use .encode()
Run Code Online (Sandbox Code Playgroud)

首先尝试解决这个问题:

def writeCache(env, cache):
            with env.begin(write=True) as txn:
                for k, v in cache.items():
                    k.encode()
Run Code Online (Sandbox Code Playgroud)

有效,但不包括变量 v 。

def writeCache(env, cache):
                with env.begin(write=True) as txn:
                    for k, v in cache.items():
                        k.encode()
                        v.encode()
Run Code Online (Sandbox Code Playgroud)

我得到以下信息:

AttributeError: 'bytes' object has no attribute 'encode'
Run Code Online (Sandbox Code Playgroud)

这与 v.encode()

小智 7

txn.put(str(k).encode(), str(v).encode())
Run Code Online (Sandbox Code Playgroud)

这对我行得通。