如何在此字典列表中获取 "price"s 值?
How can I get "price"s value in this dict list?
products = [
{"name": "samsung s6", "price": 3000},
{"name": "samsung s7", "price": 4000},
{"name": "samsung s8", "price": 5000},
{"name": "samsung s9", "price": 6000},
{"name": "samsung s10", "price": 7000}
]
for product in products:
for a, b in product.items():
print(b)
大家好。我想获取价格键的值并计算我拥有的所有物品的总价。获得它的最佳方式是什么?
要获取每个字典的价格键的值,只需使用 my_dict["key"]
语法访问它即可。这是使用 for 循环对价格求和的基本方法:
total = 0
for product in products:
total += product["price"]
print(total)
稍微高级一点的方法是使用列表理解或生成器表达式创建价格序列,并将其传递给内置的 sum
函数,如下所示:
total = sum(product["price"] for product in products)
简短版本:
print( sum( x['price'] for x in products ) )
这等同于:
newList = []
for x in products:
newList.append( x['price'] )
out = sum( newList )
print( out )
products = [
{"name": "samsung s6", "price": 3000},
{"name": "samsung s7", "price": 4000},
{"name": "samsung s8", "price": 5000},
{"name": "samsung s9", "price": 6000},
{"name": "samsung s10", "price": 7000}
]
for product in products:
for a, b in product.items():
print(b)
大家好。我想获取价格键的值并计算我拥有的所有物品的总价。获得它的最佳方式是什么?
要获取每个字典的价格键的值,只需使用 my_dict["key"]
语法访问它即可。这是使用 for 循环对价格求和的基本方法:
total = 0
for product in products:
total += product["price"]
print(total)
稍微高级一点的方法是使用列表理解或生成器表达式创建价格序列,并将其传递给内置的 sum
函数,如下所示:
total = sum(product["price"] for product in products)
简短版本:
print( sum( x['price'] for x in products ) )
这等同于:
newList = []
for x in products:
newList.append( x['price'] )
out = sum( newList )
print( out )