Python for comprehension with dict keys and values in else clause

huangapple go评论73阅读模式
英文:

Python for comprehension with dict keys and values in else clause

问题

这是我的示例如下。目标是根据另一个列表中存在的键更新字典。如果键存在于列表中,则将值加1,否则减1。我尝试了通过列表推导的方法,但出现了语法错误。通过简单的for循环,可以解决这个问题。但我正在寻找使用列表推导的方法。

Python for comprehension with dict keys and values in else clause

英文:

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.

Python for comprehension with dict keys and values in else clause

答案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.

huangapple
  • 本文由 发表于 2023年7月17日 11:28:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定