英文:
Python for comprehension with dict keys and values in else clause
问题
这是我的示例如下。目标是根据另一个列表中存在的键更新字典。如果键存在于列表中,则将值加1,否则减1。我尝试了通过列表推导的方法,但出现了语法错误。通过简单的for循环,可以解决这个问题。但我正在寻找使用列表推导的方法。
英文:
Attached is my sample in below. Aim's want to update dict based on key which is present in another list. if key is present in the list update value +1 otherwise value -1. I tried with for comprehension approach and getting syntax error. through simple for loop , will solve the problem. but i am looking for approach with for comprehension.
答案1
得分: 1
{
key: (data[key]+1 if key in data else data[key]-1)
for key in list_update_keys
}
这似乎是您试图在字典推导式中使用条件表达式,但实际上您想要的是类似这样的东西:
{
key: (data[key]+1 if key in data else data[key]-1)
for key in list_update_keys
}
但如果宽度触发了,这将导致KeyError
,因为在这种情况下,键不在字典中。
英文:
It appears you are trying to use a conditional expression in a dictionary comprehension, but you actually wanted something like:
{
key: (data[key]+1 if key in data else data[key]-1)
for key in list_update_keys
}
But this will result in a KeyError
if the wide is triggered, since in that case the key is not in the dictionary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论