How to convert a counter collection into a list
Question:
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]]
Answers:
you can 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]]
In this example I wanted to covert mis collection into a list and then into a df so I did this
lista_conteos = [list(i) for i in n_palabra.items()]
palabras = []
conteos = []
for i in range(0, len(lista_conteos)):
palabras.append(lista_conteos[i][0][0])
conteos.append(lista_conteos[i][1])
You can use most_common()
method of Counter
to turn out a list of tuples showing values together
c = Counter({2017: 102, 2018: 95, 2015: 87,})
m = c.most_common()
print(m)
>>> [(2017, 102), (2018, 95), (2015, 87)]
You can convert the result to a list of lists instead of tuples by doing this:
print([list(i) for i in c.items()])
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]]
you can 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]]
In this example I wanted to covert mis collection into a list and then into a df so I did this
lista_conteos = [list(i) for i in n_palabra.items()]
palabras = []
conteos = []
for i in range(0, len(lista_conteos)):
palabras.append(lista_conteos[i][0][0])
conteos.append(lista_conteos[i][1])
You can use most_common()
method of Counter
to turn out a list of tuples showing values together
c = Counter({2017: 102, 2018: 95, 2015: 87,})
m = c.most_common()
print(m)
>>> [(2017, 102), (2018, 95), (2015, 87)]
You can convert the result to a list of lists instead of tuples by doing this:
print([list(i) for i in c.items()])