我有一个具有相同键但不同值的字典列表。 示例:
[{ 'Price' : 100, 'Quantity' : 3 }, { 'Price' : 200, 'Quantity' : 5 }]
有没有一种方法可以一次性更新所有字典中特定键的值而不使用for循环?
也就是说,有没有办法一次性让列表中的所有字典Quantity=0?
我正在寻找性能,因为我有一个巨大的字典列表,并且我假设可能有比使用 for 循环更快的方法来做到这一点。我有。经历了多个有关堆栈溢出的问题,但没有得到任何满意的答复。
正如评论中所建议的,你可以做这样的事情(我也建议不要留在你的字典中):
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")
您可以使用以下方法实现它:
your_dictionary = [{ 'Price' : 100, 'Quantity' : 3 }, { 'Price' : 200, 'Quantity' : 5 }]
key_name = 'Quantity'
new_value = 0
list(map(lambda d: d.update({key_name: new_value}), your_dictionary))
print(your_dictionary)