Search code examples
pythonlistdefaultdict

Sort Payload with unique IDs


Im having the following piece of code:

values = defaultdict(set)
for block in scanner:
    payload = block.packet_payload_info[2]
    id, type = getId(payload)
    values[id].add(value)
    out.write(str(id) + ";" + str(typee) + ";".join(map(str, [id] + list(values[id].round(2)))) + "\n")

Im getting with this the following output as an example:

9;2;17.7999992370605479;17.299999237060547;17.799999237060547 10;2;22.39999961853027310;22.399999618530273 2;2;39.09999847412109411;20.399999618530273

Now it happens, that the payload is reading again the values and prints again the same id and prints the values again and again.

9;2;17.7999992370605479;17.299999237060547;17.799999237060547
10;2;22.39999961853027310;22.399999618530273 
2;2;39.09999847412109411;20.399999618530273
[...]
9;2;17.7999992370605479;17.299999237060547;17.799999237060547
10;2;22.39999961853027310;22.399999618530273 
2;2;39.09999847412109411;20.399999618530273

I need now a code where I have only the unique ID and the values after that, no repeating of the ids. Can someone help me how to do that in python?


Solution

  • I think the easiest thing that you can do is store the existing IDs and only proceed if the ID has not been handled yet. This code should still be improved though. A few things stand out, one of them is using a built in as a variable name - id. You should never do that, just as you should never name a variable str or list. Other improvements that you should consider is adding comments to your code and sticking to PEP8-recommended line length. I also recommend using f-strings rather than +ing strings to each other (see example).

    Below is my proposition of fixing the exact issue you mention, just remember that I have no understanding of what your code is exactly doing and what kind of objects you are dealing with.

    values = defaultdict(set)
    ids_handled = []
    for block in scanner:
        payload = block.packet_payload_info[2]
        item_id, type = getId(payload)
        if item_id not in ids_handled:
            values[item_id].add(value)
            out.write(str(id) + ";" + str(typee) + ";".join(map(str, [item_id] + list(values[item_id].round(2)))) + "\n")
            ids_handled.append(item_id)