I'm a Python newbie trying to parse a file to make a table of memory allocations. My input file is in the following format:
48 bytes allocated at 0x8bb970a0
24 bytes allocated at 0x8bb950c0
48 bytes allocated at 0x958bd0e0
48 bytes allocated at 0x8bb9b060
96 bytes allocated at 0x8bb9afe0
24 bytes allocated at 0x8bb9af60
My first objective is to make a table that counts the instances of a particular number of byte allocations. In other words, my desired output for the above input would be something like:
48 bytes -> 3 times
96 bytes -> 1 times
24 bytes -> 2 times
(for now, I'm not concerned about the memory addresses)
Since I'm using Python, I thought doing this using a dictionary would be the right way to go (based on about 3 hours' worth of reading Python tutorials). Is that a good idea?
In trying to do this using a dictionary, I decided to make the number of bytes the 'key', and a counter as the 'value'. My plan was to increment the counter on every occurrence of the key. As of now, my code snippet is as follows:
# Create an empty dictionary
allocationList = {}
# Open file for reading
with open("allocFile.txt") as fp:
for line in fp:
# Split the line into a list (using space as delimiter)
lineList = line.split(" ")
# Extract the number of bytes
numBytes = lineList[0];
# Store in a dictionary
if allocationList.has_key('numBytes')
currentCount = allocationList['numBytes']
currentCount += 1
allocationList['numBytes'] = currentCount
else
allocationList['numBytes'] = 1
for bytes, count in allocationList.iteritems()
print bytes, "bytes -> ", count, " times"
With this, I get a syntax error in the 'has_key' call, which leads me to question whether it is even possible to use variables as dictionary keys. All examples I have seen so far assume that keys are available upfront. In my case, I can get my keys only when I'm parsing the input file.
(Note that my input file can run into thousands of lines, with hundreds of different keys)
Thank you for any help you can provide.