+ 3
How do I convert a list to a dictionary?
For example, how do I convert: ['cats', 'dogs', 'cats', 'rats'] to {'cats': 2, 'dogs': 1, 'rats': 1}
4 Answers
+ 6
a = ['cats', 'dogs', 'cats', 'rats']
b = {
animal: a.count(animal)
for animal in set(a)
}
+ 3
You will have to use list comprehension, whereby you will be having both the key and values in the list
+ 2
My post corrected..
import collections
mylist = ['cats', 'dogs', 'cats', 'rats']
b = dict(collections.Counter(mylist).most_common())
print(b)
+ 1
Thanks guys.