更新列表,该列表是字典中键的值

时间:2019-03-19 07:27:32

标签: python

我有一个像这样的字典

d = {c1: l1, c2: l2, c3: l3, ......., cn: ln}

其中c1,c2,... cn是字符串,l1,l2,... l3是列表。

现在,我有一个需要更新列表的函数,用于一对变量c,x:

1。如果c在d中:

找到c的(键,值),并用x更新相应的l

2。如果c不在d中:

在d中创建一个cm:lm对

到目前为止,我尝试过的是:

if c in d:
    d.update({cn:ln.append(x)})
else:
    d.update({cm:lm.insert(x)})

但是代码无法正常工作。

任何有关为什么代码不起作用的指针都会有所帮助,欢迎提供任何有关使代码起作用的建议。

P.S:将c和x值作为参数传递给函数,所有更新均在该函数中进行。

为澄清起见,我在Windows 10上的PyCharm上运行Python 2.7。

编辑:

 A sample output

2 个答案:

答案 0 :(得分:1)

if c in d:
    # d[c] corresponds to the list you want to update
    d[c].append(x)
    # the append function directly modifies the list at d[c], 
    # so we don't have to do any re-assignment
else:
    # d[c] does not exist, so we create a new list with your item
    d[c] = [x]

答案 1 :(得分:1)

请参阅https://repl.it/repls/ExternalCornyOpendoc 示例代码如下:

d = {
  "Key1":[1,2,3],
  "Key2":[11,12,13]
}

def test(c, x):
  if c in d:
    d[c].append(x);
  else:
    d[c] = [x];
  print(d)

test("Key1", 12)
test("Key3", 122)