Reputation: 13
I'm trying to create individual dictionary entries while looping through some input data. Part of the data is used for the key, while a different part is used as the value associated with that key. I'm running into a problem (due to Python's "everything is an object, and you reference that object" operations method) with this as ever iteration through my loop alters the key set in previous iterations, thus overwriting the previously set value, instead of creating a new dict key and setting it with its own value.
popcount = {}
for oneline of datafile:
if oneline[:3] == "POP":
dat1, dat2, dat3, dat4, dat5, dat6 = online.split(":")
datid = str.join(":", [dat2, dat3])
if datid in popcount:
popcount[datid] += int(dat4)
else:
popcount = { datid : int(dat4) }
This iterates over seven lines of data (datafile
is a list containing that information) and should create four separate keys for datid
, each with their own value. However, what ends up happening is that only the last value for datid
exist in the dictionary when the code is run. That happens to be the one that has duplicates, and they get summed properly (so, at least i know that part of the code works, but the other key entries just are ... gone.
The data is read from a file, is colon (:
) separated, and treated like a string even when its numeric (thus the int()
call in the if datid in popcount
).
What am I missing/doing wrong here? So far I haven't been able to find anything that helps me out on this one (though you folks have answered a lot of other Python questions i've run into, even if you didn't know it). I know why its failing; or, i think i do -- it is because when I update the value of datid
the key gets pointed to the new datid
value object even though I don't want it to, correct? I just don't know how to fix or work around this behavior. To be honest, its the one thing I dislike about working in Python (hopefully once I grok it, I'll like it better; until then...).
Upvotes: 1
Views: 339
Reputation: 22294
Simply change your last line
popcount = { datid : int(dat4) } # This does not do what you want
This creates a new dict
and assignes it to popcount
, throwing away your previous data.
What you want to do is add an entry to your dict
instead:
popcount[datid] = int(dat4)
Upvotes: 1