Search code examples
python-3.xflask

How can I query the same keys and only output them as a number?


I have a list where I want to filter the number of a certain key, depending on whether another key exists or not.

Data: DEV_DATA: [{'.cn': 'DEVICE200002', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff23fd96'}, {'.cn': 'DEVICE200003', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff245135'}, {'.cn': 'DEVICE200111', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff24ab22'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff252729', '.cn': 'DEVICE200112'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff25a19d', '.cn': 'DEVICE200222'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff26405b', '.cn': 'DEVICE200057', 'host_serial': 'HO-STA-2103-2A77'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff267f56', '.cn': 'DEVICE200106', 'host_serial': 'HO-STA-2011-0A66'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff26cbb7', '.cn': 'DEVICE200116', 'host_serial': 'HO-STA-2011-0B14'}, {'host_serial': 'HO-STA-2011-0BA3', '.cn': 'DEVICE200134', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff270a6c'}, {'host_serial': 'HO-STA-2011-0BA9', '.cn': 'DEVICE200138', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff27497b'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff23a830', '.cn': 'DEVICE200001'}]

Query:

with_serial = []
for e in dev_data:
    if 'host_serial' in e.keys():
        with_serial = e['.cn']
            
        print("With_Serial: ", with_serial)


not_serial = []
for e in dev_data:
    if 'host_serial' not in e.keys():
        not_serial = e['.cn']
            
        print("Not_Serial: ", not_serial)

Output is:

With_Serial:  DEVICE200057
With_Serial:  DEVICE200106
With_Serial:  DEVICE200116
With_Serial:  DEVICE200134
With_Serial:  DEVICE200138

Not_Serial:  DEVICE200001
Not_Serial:  DEVICE200002
Not_Serial:  DEVICE200003
Not_Serial:  DEVICE200111
Not_Serial:  DEVICE200112
Not_Serial:  DEVICE200222

What i want to get is:

With_Serial:  5

Not_Serial:  6

I have tried various solutions, but I can't get it to work. Any idea how can i solve this?


Solution

  • Instead of a list, use an integer counter and increment it depending on your condition:

    with_serial = 0
    not_serial  = 0
    for d in DEV_DATA:
        if 'host_serial' in d:
            with_serial += 1
        else:
            not_serial  += 1
            
    with_serial
    # 5
    
    not_serial
    # 6
    

    Or a pythonic approach using collections.Counter:

    from collections import Counter
    
    out = Counter('with_serial' if 'host_serial' in d else 'not_serial'
                  for d in DEV_DATA)
    

    Output:

    Counter({'not_serial': 6, 'with_serial': 5})