Getting 'int' object is not iterable

后端 未结 3 693
慢半拍i
慢半拍i 2021-01-25 20:37
    cat_sums[cat] += value
TypeError: \'int\' object is not iterable

My input is this:

defaultdict(, {\'composed\'         


        
3条回答
  •  不知归路
    2021-01-25 21:35

    If anyone is getting this error inside a Django template …

    When you do:

    {% for c in cat_sums.keys %}
    

    then, behind the scenes, the Django template language first tries a cat_sums['keys'] lookup. Normally this would fail and Django would next look for a method. But since this is a defaultdict, the default value gets stored instead.

    If the dict was created with

    cat_sums = defaultdict(int)
    

    What gets executed is:

    for c in cat_sums['keys']:
    

    i.e.,

    for c in 0:
    

    which quite rightly throws an error as the value 0 is not iterable.

    Resolution? Pass dict(cat_sums) inside the context so the view gets a regular dict.

提交回复
热议问题