Graphics Reference
In-Depth Information
Tip
Python hashmaps are an efficient alternative to lists. You can quickly
add or remove items without iterating across a list.
The first line inside the function (
if name in nodemap:
) checks to
see whether the key
name
has already been used in the hashmap. If
false
(such as the first time calling
addNode
), the
else
section is called. In
the
else
section, a new node is defined using name:value pairs (
node =
{"nodeid": name, "count": 1
), and then the node is added to the
nodemap
using the key (
nodemap[name] = node
).
On successive calls to the function
addNode
, in some cases the node already
exists, and
name in nodemap
will be
true
. In this case, the variable
node
will be assigned to the already existing node object retrieved using the
key
node = nodemap[name]
. With the retrieved node, any value stored
with this node can be adjusted using the appropriate name to access it. For
example, incrementing the count for the number of times this name has
occurred is done with
node["count"] += 1
.
Writing Out the Node Hashmap
The final step is to write out the file, which steps through all the nodes in
nodemap
and writes out a node on each successive row in the file.
#write out nodes
with open("nodes.txt", "w", newline="") as nodefile:
formatter = csv.writer(nodefile, delimiter="\t")
formatter.writerow(["Id","Count"])
for name in nodemap:
node = nodemap[name]
formatter.writerow([node["nodeid"],node["count"],
])
Opening the file is similar to reading, except it's set for writing (
"w"
). A
header row is written first, and then a loop iterates through each key (that
is, name) in the hashmap (
for name in nodemap:
).