pythonlistcounter

How to convert a counter collection into a list


I need to convert a the output of a counter collection into a list

My counter output is:

Counter({2017: 102, 2018: 95, 2015: 87,})

I want to convert this into something like this:

[[year,count],[year,count],[year,count]]

Solution

  • Use Counter(...).items()

    from collections import Counter
    
    cnt = Counter({2017: 102, 2018: 95, 2015: 87})
    
    print(cnt.items())
    >>> dict_items([(2017, 102), (2018, 95), (2015, 87)])
    

    your can convert this to the format you wanted:

    your_list = [list(i) for i in cnt.items()]
    
    print(your_list)
    >>> [[2017, 102], [2018, 95], [2015, 87]]