更新作为字典中键值的列表

我有一本字典,如:


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

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


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


1. 如果 c 在 d 中:


找到c的(key, value),用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。


编辑:

http://img4.mukewang.com/61b1a8460001553906180287.jpg


肥皂起泡泡
浏览 252回答 2
2回答

小唯快跑啊

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-assignmentelse:    # d[c] does not exist, so we create a new list with your item    d[c] = [x]

一只名叫tom的猫

请参阅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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python