Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.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 使用JSON文件中的信息创建字典_Python_Json_Dictionary - Fatal编程技术网

Python 使用JSON文件中的信息创建字典

Python 使用JSON文件中的信息创建字典,python,json,dictionary,Python,Json,Dictionary,我有一个JSON文件,其中包含您可以在附件中看到的信息: 我需要一些帮助为每个导演创建一个“类型词典”,如:{GenreName:Number},其中“Number”对应于导演“创建”的属于该类型的电影数量 例如,检查“Sidney Lumet”字典应如下所示: {你的戏剧:2,你的战争:1,你的冒险:1,你的惊悚片:2,你的犯罪:1} 因为在文件中,您可以读取: "Before the Devil Knows You're Dead;2007": { "DIRECTORS": [

我有一个JSON文件,其中包含您可以在附件中看到的信息:

我需要一些帮助为每个导演创建一个“类型词典”,如:{GenreName:Number},其中“Number”对应于导演“创建”的属于该类型的电影数量

例如,检查“Sidney Lumet”字典应如下所示: {你的戏剧:2,你的战争:1,你的冒险:1,你的惊悚片:2,你的犯罪:1}

因为在文件中,您可以读取:

  "Before the Devil Knows You're Dead;2007": {
    "DIRECTORS": [
      "Sidney Lumet"
    ], 
    "GENRES": [
      "Crime", 
      "Drama", 
      "Thriller"
   "Fail-Safe;1964": {
    "DIRECTORS": [
      "Sidney Lumet"
    ], 
    "GENRES": [
      "Adventure", 
      "Drama", 
      "Thriller", 
      "War"

我在标题中错误地解释了我需要什么。
我的问题不是如何检索信息(我知道json模块,我知道如何访问它的元素),但我需要帮助为每个控制器创建特定的字典。

这不是python问题,而是算法问题。所有与pyhton相关的内容都是

with open('file.json') as f:    
    data = json.load(f)
然后,您需要浏览所有电影并计算每种类型的电影,例如:

directors_dict = {}
for film_name, film in data.iteritems():
    for dir in film['DIRECTORS']:
        if not dir in directors_dict:
            directors_dict[dir] = {}
        for genr in film['GENRES']:
            if not genr in directors_dict[dir]:
                directors_dict[dir][genr] = 0
            directors_dict[dir][genr] += 1

 print(directors_dict)

PS:我没有测试这段代码,我甚至不知道确切的格式是什么(你的文件需要从谷歌硬盘访问)。您应该使用print()或debugger调试和纠正错误。

可能重复See pythons标准库,有一个很棒的json库我已经在使用json库访问每个元素(控制器、流派和ofc标题,我不能做的是创建特定的“流派”字典-我的错我写了一个错误的标题)。你的数据来自哪里?您将数据存储在哪里?在Python源代码中(坏主意),从文件中,从数据库中…?是的,你是对的,不管怎样,我的问题是关于算法和Python的(我不确定我自己是否能够用Python编写代码)。谢谢