【问题标题】:Python dictionary syntax to initiate a dictionary [duplicate]启动字典的Python字典语法[重复]
【发布时间】:2018-10-13 04:56:56
【问题描述】:

谁能告诉我以下 Python 语法? 如何解释以下 Python 字典?

graph["start"] = {}
# Map "a" to 6
graph["start"]["a"] = 6

它是否启动一个数组并将字典分配为其元素? 还是它启动了一个以“开始”为键、字典为值的地图? 或者变量名是 graph["start"] 并且它的类型是字典? 我只是糊涂了

【问题讨论】:

  • 这段代码本身只会抛出一个 NameError。 graph 变量从未定义。
  • 另请注意,Python 变量没有类型化。
  • 查看源代码后。在文件中,第一行是 graph = {}。因此,该图已被定义为字典。谢谢!

标签: python


【解决方案1】:

假设前面的代码已将变量“graph”绑定到字典。那么:

graph["start"] = {}

向“图表”添加键:值对,其中键是“开始”,值是新字典。

行:

graph["start"]["a"] = 6

在“start”键下查找“graph”中存储的对象,并为其添加一个新的键:值对,其中键为“a”,值为 6。

这两行加起来相当于:

graph["start"] = {"a":6}

graph["start"] = dict(a=6)

【讨论】:

    【解决方案2】:

    我假设“图表”已经被定义为字典。
    这是一个小例子:

    graph = {}
    graph['a'] = {}  # The key is 'a', it references a dictionary.
    graph['a']['b']=2  # In this new dictionary, we'll set 'b' to 2.
    print(graph) #{'a': {'b': 2}}
    

    您的语法正确。 :-)
    我也不认为 Python 中存在数组...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-18
      • 2020-06-14
      • 1970-01-01
      • 2018-06-02
      • 2018-03-27
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      相关资源
      最近更新 更多