Best way to turn word list into frequency dict

后端 未结 8 498
无人及你
无人及你 2020-12-03 17:07

What\'s the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?<

相关标签:
8条回答
  • 2020-12-03 17:51

    I think using collection library is the easiest way to get it. But If you want to get the frequency dictionary without using it then it's another way,

    l = [1,4,2,1,2,6,8,2,2]
    d ={}
    for i in l:
        if i in d.keys():
            d[i] = 1 + d[i]
        else:
            d[i] = 1
    print (d)
    

    op:

    {1: 2, 4: 1, 2: 4, 6: 1, 8: 1}
    
    0 讨论(0)
  • 2020-12-03 17:54

    Actually, the answer of Counter was already mentioned, but we can even do better (easier)!

    from collections import Counter
    my_list = ['a', 'b', 'b', 'a', 'b', 'c']
    Counter(my_list)  # returns a Counter, dict-like object
    >> Counter({'b': 3, 'a': 2, 'c': 1})
    
    0 讨论(0)
提交回复
热议问题