[英]How to update multiple dictionary values based on a condition?
I have a dictionary which looks like: 我有一本字典,看起来像:
dict = {'A':[1,2], 'B':[0], 'c':[4]}
need it to look like: 需要它看起来像:
dict = {'A':[1,2], 'B':[0,0], 'c':[4,0]}
What I am doing right now: 我现在正在做什么:
dict = {x: y+[0] for (x,y) in dict.items() if len(y) < 2}
which generates: 产生:
dict = {'B':[0,0], 'c':[4,0]}
any idea how I could avoid eliminating those who do not meet the condition? 知道如何避免淘汰那些不符合条件的人吗?
You're almost there. 你快到了。 Try:
尝试:
my_dict = {x: y + [0] if len(y) < 2 else y
for (x,y) in dict.items()}
(as mentioned by jp_data_analysis, avoid naming variables after builtins like dict
) (如jp_data_analysis所述,请避免在诸如
dict
内置变量之后命名变量)
This is one way. 这是一种方式。
Note : do not name variables after classes, eg use d
instead of dict
. 注意 :不要在类后命名变量,例如,使用
d
而不是dict
。
d = {'A':[1,2], 'B':[0], 'c':[4]}
d = {k: v if len(v)==2 else v+[0] for k, v in d.items()}
# {'A': [1, 2], 'B': [0, 0], 'c': [4, 0]}
You can use dictionary comprehension: 您可以使用字典理解:
d = {'A':[1,2], 'B':[0], 'c':[4]}
new_d = {a:b+[0] if len(b) == 1 else b for a, b in d.items()}
Also, it is best practice not to assign variables to names shadowing common builtins, such as dict
, as you are then overriding the function in the current namespace. 另外,最好的做法是,不要在隐藏通用内建函数的名称(例如
dict
上分配变量,因为这样您将覆盖当前名称空间中的函数。
Your code is almost correct. 您的代码几乎是正确的。 Your problem is that you're filtering out any lists bigger than
2
. 您的问题是您要过滤掉任何大于
2
列表。 What you need to do instead is simply place them in the new dictionary unchanged. 您需要做的就是简单地将它们放置在新字典中,而无需更改。 This can be done using the ternary operator .
这可以使用三元运算符来完成。 It has the form
value1 if condition else value2
. value1 if condition else value2
则格式为value1 if condition else value2
。
Also, if you want a more general way to pad every list in your dictionary to be of equal length, you can use map
and max
. 同样,如果您希望以更通用的方式将字典中的每个列表都填充为相等的长度,则可以使用
map
和max
。
Here is your code with the above modifications: 这是经过上述修改的代码:
>>> d = {'A':[1, 2], 'B': [0], 'c': [4]}
>>>
>>> max_len = max(map(len, d.values()))
>>> {k: v + [0] * (max_len - len(v)) if len(v) < max_len else v for k, v in d.items()}
{'A': [1, 2], 'B': [0, 0], 'c': [4, 0]}
>>>
A generalized way: 通用方式:
d = {'A':[1,2], 'B':[0], 'c':[4]}
m = max(len(v) for v in d.values())
for k, v in d.items():
if len(v) < m:
d[k].extend([0 for i in range(m-len(v))])
You were very close, just use update()
: 您非常接近,只需使用
update()
:
d = {'A':[1,2], 'B':[0], 'c':[4]}
d.update({x: y+[0] for (x,y) in d.items() if len(y) < 2})
d
# {'A': [1, 2], 'B': [0, 0], 'c': [4, 0]}
Like others have said, don't use reassign reserved names like dict
, it's a one way street down to debugging hell. 就像其他人所说的,不要使用像
dict
这样的重新分配保留名称,这是调试地狱的唯一途径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.