It would be much easier to answer if you provided a sample of your input data, as it would help finding out where your code is wrong. Without that, we can only make wild guesses or shots in the dark.
I would also suggest that you use indentation consistently, it would probably help yourself finding out what you're doing wrong.