如何将一个字典值多次添加到数组?

时间:2018-10-29 18:32:50

标签: python arrays dictionary typeerror extend

我想将f1的值两次添加到数组中,但是extend()方法给我这个错误?

  

TypeError:“ int”对象不可迭代

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

是否有另一种方法可以将f1中的值两次添加到数组mo中?

最好

帕特里克

2 个答案:

答案 0 :(得分:0)

问题在于extend带有一个可迭代的对象(列表,元组等),但是您传递的是单个值(int)。

您想改用append

这是一个例子:

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

编辑:如果要将nval出现在mo中,其中n等于{ key中的{1}},则可以执行以下操作:

s

答案 1 :(得分:0)

.extend()方法将列表添加到当前列表中,要添加值,应使用.append()方法

我认为您想要的代码就是这个

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