+ 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}

17th Mar 2020, 9:59 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
4 Answers
+ 6
a = ['cats', 'dogs', 'cats', 'rats'] b = { animal: a.count(animal) for animal in set(a) }
17th Mar 2020, 10:15 PM
HonFu
HonFu - avatar
+ 3
You will have to use list comprehension, whereby you will be having both the key and values in the list
17th Mar 2020, 10:10 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 2
My post corrected.. import collections mylist = ['cats', 'dogs', 'cats', 'rats'] b = dict(collections.Counter(mylist).most_common()) print(b)
17th Mar 2020, 10:25 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Thanks guys.
17th Mar 2020, 11:54 PM
Tomiwa Joseph
Tomiwa Joseph - avatar