1

Could anyone let me know the following Python syntax? How do I interpret the following Python dictionary?

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

Does it initiate an Array and assign the dictionary as its element? or it initiated a map with "start" as the key and dictionary as the value? or the variable name is graph["start"] and it's type is a dictionary? I just got confused

user3422290
  • 253
  • 5
  • 18

2 Answers2

1

Assume that previous code has bound the variable "graph" to a dictionary. Then:

graph["start"] = {}

adds to "graph" a key:value pair where the key is "start" and the value is a new dictionary.

The line:

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

looks up the object stored in "graph" under the key "start", and adds to it a new key:value pair where the key is "a" and the value is 6.

The two lines together are the equivalent of:

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

or

graph["start"] = dict(a=6)
Paul Cornelius
  • 9,245
  • 1
  • 15
  • 24
0

I assume 'graph' has been defined as a dictionary already.
Here's a small example:

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}}

You've got your syntax right. :-)
I also didn't think arrays existed in Python...