函数返回列表为字典?

时间:2016-11-03 17:43:11

标签: python python-3.x dictionary return

我的下面的功能是获取值列表并返回重复计数。我设法让它计数和打印,但我的任务是将其作为字典返回。我一直在努力以正确的格式返回,有什么建议吗?

def counts(values):
    d = {}
    for val in values:
        d.setdefault(val,0)
        d[val] += 1
    for val, count in d.items():
        d = ("{} {}".format(val,count))
        return d
counts([1,1,1,2,3,3,3,3,5]) # Should return →  {1: 3, 2: 1, 3: 4, 5: 1}

1 个答案:

答案 0 :(得分:1)

只需返回创建的字典:

def counts(values):
    d = {}
    for val in values:
        d.setdefault(val,0)
        d[val] += 1
    return d

收率:

>>> counts([1,1,1,2,3,3,3,3,5])
{1: 3, 2: 1, 3: 4, 5: 1}

当然,正如摩西指出的那样,Counter是为此而建的,所以只需使用它:

from collections import Counter

def counts(values):
    return dict(Counter(values))