简体   繁体   English

如何更新字典以添加到 Python 中的列表

[英]How to update a dictionary to add to a list in Python

If I have the dictionary如果我有字典

d = {
  "group1": [0],
  "group2": [3,7]
}

How can I update the list to add another value to it.如何更新列表以向其添加另一个值。

I thought我想

d.update({"group1": [4]})

would add the number 4 and that the new dictionary would be将添加数字 4,新字典将是

{
  "group1": [0,4],
  "group2": [3,7]
}

but this is not the case when I try it.但是当我尝试时情况并非如此。

d["group1"].append(4)

Just use the .append() method of the list.只需使用列表的.append()方法。 You can access d['group1'] and that is your list.您可以访问d['group1'] ,这是您的列表。

d['group1'].append(4)

If your goal is to update a dictionary by appending key:values from another one, you can do it like this:如果您的目标是通过附加另一个字典的 key:values 来更新字典,您可以这样做:

d = { "group1": [0],
      "group2": [3,7],
      "group3": [8]
    }
u = { "group1": [4],
      "group2": [5,9],
      "group4": [1,2]
    }

d = { g:d.get(g,[]) + u.get(g,[]) for g in {*d,*u} }

# {'group1': [0, 4], 'group4': [1, 2], 'group2': [3, 7, 5, 9], 'group3': [8]}

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

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