Jam Jam - 2 months ago 10x
Python Question

Building a HashMap using Python in a loop. Clarification needed

I am running in a loop and and parsing a string. That string ultimately contains 2 items a host and application running on a host. As expected a host runs multiple applications. I'd like to store it all in one data structure where host is used as a key.

Below is my failed attempt. Please help me understand why only the last element is being saved in the host = app format.

What i expect to see
host = app1, app2 etc
What i see
Host = app2 (always last)

data = dict()

def add(line):
l = line.split("/")
host = l[0].strip()
app = l[-1].strip()


for entry in env:
if "/" not in entry: continue

print data


The problem is with data[host].append(app)

Would append the value of app to the list (or similar) stored as data[host]

When you run this, the value of data[host] is not set, and so you can't append to it. You will get a KeyError. Perhaps you meant data[host] = app? or...

except KeyError:
    data[host] = [app]