pythonlistpython-3.xdictionarymissing-data

Counting how many values were attributed to a key an a python (3.2) dictionary


I am sure this is silly, but I simply cannot get around it. I have a dictionary, like this, with unequal number of values for each key:

'John greased ': ['axle', 'wheel', 'wheels', 'wheel', 'engine', ''], 
'Paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''], 
'Tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'], 
'Lisa plowed ': ['field', 'field', '', '', '', ''],

I want to know how many values there are for each key, not each unique value but how many tokens there are per key, repeated or not. So I would have a result like:

John greased  5
Paul alleged  5
Tracy freed  6
Lisa plowed  2

I was trying to use this to work it out using the code bellow:

for key, value in sorted(result.items()):
         print(key, len(value)) 

But because of the missing values all the lengths turn out to be the same. Any ideas on how to solve this or where to find it out? Thanks a lot for any help.


Solution

  • One way to solve this, is by changing your last line:

    print(key, len([item for item in value if item])) 
    

    So your complete code:

    ITEMS = {
        'John greased ': ['axle', 'wheel', 'wheels', 'wheel', 'engine', ''],
        'Paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''],
        'Tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'],
        'Lisa plowed ': ['field', 'field', '', '', '', ''],
    }
    
    for key, value in ITEMS.items():
        #print value
        print(key, len([item for item in value if item]))
    

    You can also use filter with bool:

    print(key, len(filter(bool, value)))
    

    So, the loop:

    for key, value in ITEMS.items():
        #print value
        print(key, len(filter(bool, value)))
    

    You need to apply list over filter like so print(key, len(list(filter(bool, value)))) in Python 3.