Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:uu dict_uuu必须设置为字典,而不是';unicode';_Python_Json_Dictionary_Unicode_Ipython - Fatal编程技术网

Python TypeError:uu dict_uuu必须设置为字典,而不是';unicode';

Python TypeError:uu dict_uuu必须设置为字典,而不是';unicode';,python,json,dictionary,unicode,ipython,Python,Json,Dictionary,Unicode,Ipython,我从git克隆了一个库,我只是设法使用了savePlayerDictionary方法 我存储了json文件,一切看起来都很好 但是 当我尝试使用loadPlayerDictionary时,会出现以下错误: TypeError: __dict__ must be set to a dictionary, not a 'unicode' 我的代码: def savePlayerDictionary(playerDictionary, pathToFile): """ Saves p

我从git克隆了一个库,我只是设法使用了
savePlayerDictionary
方法

我存储了json文件,一切看起来都很好

但是

当我尝试使用loadPlayerDictionary时,会出现以下错误:

TypeError: __dict__ must be set to a dictionary, not a 'unicode'
我的代码:

def savePlayerDictionary(playerDictionary, pathToFile):
    """
    Saves player dictionary to a JSON file
    """
    player_json = {name: player_data.to_json() for name, player_data in playerDictionary.items()}
    json.dump(player_json, open(pathToFile, 'wb'), indent=0)


def loadPlayerDictionary(pathToFile):
    """
    Loads previously saved player dictionary from a JSON file
    """
    result = {}
    with open(pathToFile, "r") as f:
        json_dict = json.load(f)
        for player_name in json_dict:
            parsed_player = Player(None,None,False)
            parsed_player.__dict__ = json_dict[player_name]
            result[player_name] = parsed_player
    return result
其中
player\u data.to\u json()
实现为:

def to_json(self):
    return json.dumps(self.__dict__)
我运行的代码是:

get_ipython().magic(u'matplotlib inline')
import basketballCrawler as bc
import matplotlib.pyplot as plt

players = bc.loadPlayerDictionary("myJson.json")

您正在将播放器数据编码为JSON,然后将整个字典映射名称重新编码为JSON,从而为该映射的值生成双重编码的JSON数据

解码时,只解码名称数据映射,而不是每个播放器的数据。您需要分别对其进行解码:

parsed_player = Player(None,None,False)
parsed_player.__dict__ = json.loads(json_dict[player_name])
如果您不将
编码为_json()
,这会更容易:

(我使用了作为更简洁的函数来获得相同的字典)


如果你所做的是坚持你的玩家数据,那么考虑使用替代;它速度更快,功能更全面,无需使用

\uuuu dict\uuu
属性进行单独的歌曲和舞蹈。有一个名为的包装器模块,它构建在
pickle
的基础上,甚至可以为对象创建一个持久化的字典。

首先为什么要分配给
\uuuu dict\uuu
?我会使用
\u dict\u.update()
。但是很明显,
json\u dict[player\u name]
不是字典。to\u json()方法返回什么?to\u json方法是:def to\u json(self):return json.dumps(self.\u dict\u)生成一个字典。提供一个小样本JSON文件,以便加载操作再现问题。删除不必要的代码,例如save,因为它可以工作,如果提供它生成的JSON文件,则不需要它。提供完整的回溯,以便我们可以看到它是如何失败的。因此,您将两次编码为JSON。不要那样做;只返回
\uuuu dict\uuuuuu
,或者确保加载时解码两次。
def to_json(self):
    return vars(self)