-4

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()

    data[host].append(app)

for entry in env:
    if "/" not in entry: continue
    add(entry)

print data
James Raitsev
  • 92,517
  • 154
  • 335
  • 470
  • 1
    Possible duplicate of [How does collections.defaultdict work?](http://stackoverflow.com/questions/5900578/how-does-collections-defaultdict-work) – Wayne Werner Aug 01 '16 at 20:17
  • 1
    This would fail with a `KeyError`, not only return the last item. This REALLY needs a [mcve]. – Morgan Thrapp Aug 01 '16 at 20:21

3 Answers3

1

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

try:
    data[host].append(app)
except KeyError:
    data[host] = [app]
James K
  • 3,692
  • 1
  • 28
  • 36
0

data[host].append(app)

You assume host is in the dict, which is not true for the first time you append to it.

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
0

This is what I was looking for. Thank you to all those trying to help

if host in data:
    data[host].append(app)
else:
    data[host] = [app]
James Raitsev
  • 92,517
  • 154
  • 335
  • 470