英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论