Skip to content Skip to sidebar Skip to footer

Count Items In Dictionary

I need to count the the different IDENTIFIERS and print a number count for the them. The information comes from a data stream that looks like this: IDE

Solution 1:

You could use collections.Counter, but a collections.defaultdict will be sufficient for this case:

from collections import defaultdict

defRECEIVE(COMMAND):
    counts = defaultdict(int)

    # <your code>
    IDENTIFIER = SPLITLINE[1]
    counts[IDENTIFIER] += 1# <rest of your code># <whenever you want to see how many times some identifier has appeared>print(counts[SOME_IDENTIFIER])

Solution 2:

You could, of course, use simple gnu tools like

receivetest -f=/dev/pcan33 | cut -f 5 | uniq | wc -l

But if you insist on using python...

identifiers = set(line.split()[4] for line in lines)

Solution 3:

If you just want a dictionary to count objects you could do something like this:

id_count = {}
defrecieve():
    # insert your subprocess and read here, change the loopfor line in identifiers.split('\n'):
    if re.match(r"^\d+.*$",line):
        identifier = line.split()[4]
        if identifier in id_count.keys():
            id_count[identifier] += 1else:
            id_count[identifier] = 1

afterwards you can print or access the dict to see how many times you received each identifier

Solution 4:

>>>DICT = {}>>>for LINE in LINES:...  SPLITLINE = LINE.split()...try:...     DICT[SPLITLINE[4]] = DICT[SPLITLINE[4]] + 1...except:...     DICT[SPLITLINE[4]] = 1...>>>DICT
{'0x0000069a': 5, '0x00000690': 5, '0x00000688': 1, '0x00000663': 5, '0x0000069e': 5}

Post a Comment for "Count Items In Dictionary"