繁体   English   中英

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

[英]Update a list which is a value to a key in a dictionary

我有一本字典,例如:

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)})

但是代码无法按预期工作。

关于为什么代码不起作用的任何指示都将是有帮助的,欢迎提供任何有关使该代码起作用的建议。

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

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

编辑:

样本输出

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]

请参见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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM