Search code examples
pythonarraysdictionarytypeerrorextend

How to add one dictionary value multiple times to an array?


I want to add the value from f1 two times to an array, but the extend() method gives me this error?

TypeError: 'int' object is not iterable

s = ("f1", "f1")
mo = []
for key, val in shiftweek.items():
    if key in s:
        mo.extend(val)

Is there another way to add the value from f1 twice to the array mo?

Best,

Patrick


Solution

  • The issue is that extend takes an iterable object (list, tuple, etc), but you're passing a single value (int).

    You want to use append instead.

    Here's an example:

    s = ("f1", "f1")
    mo = []
    for key, val in shiftweek.items():
        if key in s:
            mo.append(val)
    

    Edit: if you want to put n occurrences of val in mo where n is equal to the number of occurrences of key in s, then you can do something like this:

    s = ("f1", "f1")
    mo = []
    for key, val in shiftweek.items():
         n = s.count(key)
         mo.extend([val] * n)