列出字典

时间:2019-02-26 20:58:24

标签: python

所以我正在处理一个由字典及其对应值组成的列表。所以我的问题是如何为关键清单编号创建一个名为max_value的变量。一个if语句,可以选择max_value。到目前为止,我已经尝试过:

max_value = 0     拖曳汽车中的数量:

if "inventory_number" in cars:

   if int(cars['inventory_number']) >= int(max_value):

     max_value = int(cars['inventory_number'])

towed_cars=
[{"color":"RED",
"inventory_number":"2870803",
"make":"GMC",
"plate":"AX21690",
"state":"IL",
"style":"LL",
"tow_date":"2019-02-16T00:00:00.000",
"tow_facility_phone":"(773) 568-8495",
"towed_to_address":"10300 S. Doty"}
,
{"color":"SIL",
"inventory_number":"2870715",
"make":"CHEV",
"plate":"AV21919",
"state":"IL",
"style":"4D",
"tow_date":"2019-02-16T00:00:00.000",
"tow_facility_phone":"(773) 568-8495",
"towed_to_address":"10300 S. Doty"}]

2 个答案:

答案 0 :(得分:1)

您需要一个for循环对其进行迭代:

max_value = 0

for car in cars:
     if "inventory_number" in car:
         inventory_number = int(car['inventory_number'])
         if inventory_number > max_value:
              max_value = inventory_number

答案 1 :(得分:1)

您也可以使用generator comprehension

max(int(d.get('inventory_number', 0)) for d in towed_cars)

2870803