简体   繁体   English

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

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

I have a dictionary like: 我有一本字典,例如:

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

where c1, c2,.... cn are strings and l1, l2,... l3 are lists. 其中c1,c2,... cn是字符串,l1,l2,... l3是列表。

Now, I have a function where the list needs to be updated, for a pair of variables c, x: 现在,我有一个需要更新列表的函数,用于一对变量c,x:

1. if c is in d: 1.如果c在d中:

Find the (key, value) for c, and update the corresponding l with x 找到c的(键,值),并用x更新对应的l

2. if c not in d: 2.如果c不在d中:

Create a cm: lm pair in d 在d中创建一个cm:lm对

So far, what I've tried is: 到目前为止,我尝试过的是:

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

But the code isn't working as expected. 但是代码无法按预期工作。

Any pointers as to why the code not working would be helpful, and any suggestions for the code which can make it work are welcome. 关于为什么代码不起作用的任何指示都将是有帮助的,欢迎提供任何有关使该代码起作用的建议。

PS: The c and x values are passed as arguments to a function, where all the updating happens. PS:c和x值作为参数传递给函数,所有更新均在该函数中进行。

For clarification, I'm running Python 2.7, on PyCharm, on Windows 10. 为了澄清起见,我在Windows 10上的PyCharm上运行Python 2.7。

Edit: 编辑:

样本输出

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]

Please see https://repl.it/repls/ExternalCornyOpendoc Example code as below: 请参见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