如何在不使用for循环的情况下更新多个字典的键值对。

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

How to update multiple dictionary key-value without using for loop

问题

我有一个具有相同键但不同值的字典列表。
示例:

[{ 'Price' : 100, 'Quantity' : 3 }, { 'Price' : 200, 'Quantity' : 5 }]

是否有一种方法可以一次性更新所有字典中特定键的值,而无需使用for循环?

也就是说,是否有一种方法可以一次性将所有字典中的Quantity设置为0?

我寻求性能,因为我有一个大型的字典列表,我认为可能有一种比使用for循环更快的方法来做到这一点。我已经查看了stackoverflow上的多个问题,但没有得到令人满意的答案。

英文:

I have a list of dictionaries with the same keys but different values.
Example:

[{ 'Price' : 100, 'Quantity' : 3 }, { 'Price' : 200, 'Quantity' : 5 }]

Is there a way to update the value of a particular key in all dictionaries in one go without using for loop?

That is, is there a way to make Quantity=0 for all dictionaries in the list in one go?

I am looking for performance since I have a huge list of dictionaries, and I'm under the assumption that there may be a faster way to do this than using a for loop. I have. gone through multiple questions on stack overflow but did not get any satisfactory response.

答案1

得分: 2

如评论中提出的建议,您可以这样做(我也建议不要继续使用您的字典):

import pandas as pd

d1 = {"price": 10, "qty": 100}
d2 = {"price": 50, "qty": 110}

# 从字典创建数据框
df = pd.DataFrame([d1, d2])

# 一次性处理列中的所有值
df["qty"] = 0

print(df)

# 如果您真的想要恢复您的字典,可以这样做
d1, d2 = df.to_dict("records")
英文:

As proposed in comments, you can do something like this (I also recommend not to stay with your dictionaries):

import pandas as pd

d1 = {"price": 10, "qty": 100}
d2 = {"price": 50, "qty": 110}

# create dataframe from dictionaries
df = pd.DataFrame([d1, d2])

# process all values in the column at once
df["qty"] = 0

print(df)

# if you really want your dictionaries back, you can do this
d1, d2 = df.to_dict("rows")

huangapple
  • 本文由 发表于 2023年5月24日 18:48:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322694.html
匿名

发表评论

匿名网友

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

确定