繁体   English   中英

从多个字典列表中返回特定键中具有最高值的字典

[英]Return the dictionary from multiple lists of dictionaries with the highest value in a specific key

我有以下两个字典列表:

    regionA = [dict(is_buy_order=True, price=1000, type=1),
               dict(is_buy_order=True, price=100, type=2),
               dict(is_buy_order=False, price=10, type=2)]
    regionB = [dict(is_buy_order=False, price=10, type=1),
               dict(is_buy_order=True, price=100, type=1),
               dict(is_buy_order=True, price=1000, type=2)]

考虑到来自 regionA 和 regionB 的数据,我想返回类型 1 和类型 2 的键“价格”和键“is_buy_order”中值“真”的字典。

我已经看到了适用于单个字典列表但不能使它们与集合一起使用的示例(例如,从特定键中具有最高值的字典列表中返回字典),我想知道是否有直接的方法做。

(这里的第一个问题:让我知道是否需要澄清,感谢您的帮助!)

您可以通过执行以下操作来做到这一点:

both_regions = regionA + regionB
result = sorted([d for d in both_regions if d['is_buy_order']],
                key=lambda x: x['price'], reverse=True)[0]

output

{'is_buy_order': True, 'price': 1000, 'type': 1}

您可以将字典集转换为 pandas dataframe,它会让您的生活更轻松:(这不是完整的代码,但沿着这些线......)

import pandas as pd
Region = dict(regionA,regionB)
df = pd.DataFrame(Region, columns= ['Region','BuyOrder', 'Price','Type'])
df.sort_values(by=['Price'], inplace=True)
regionA = [dict(is_buy_order=True, price=1000, type=1),
  dict(is_buy_order=True, price=100, type=2),
  dict(is_buy_order=False, price=10, type=2)]

regionB = [dict(is_buy_order=False, price=10, type=1),
               dict(is_buy_order=True, price=100, type=1),
               dict(is_buy_order=True, price=1000, type=2)]

c = regionA + regionB
type1 = dict(price=0)
type2 = dict(price=0)
for item in c:
  if (type1["price"]  < item["price"]) and item["is_buy_order"] and item["type"]==1:
    type1 = item
  if (type2["price"] < item["price"]) and item["is_buy_order"] and item["type"]==2:
    type2 = item

print('type1 max price', type1)
print('type2 max price', type2)

这应该有效。 首先,我将列表regionAregionB连接成一个列表total_data 然后对于每种类型,我从满足is_buy_order为 true 且type为相应类型的约束的所有订单中找到最高价格。

total_data = regionA + regionB    
maxType1 = max([order['price'] for order in total_data if order['is_buy_order'] and order['type'] == 1])
maxType2 = max([order['price'] for order in total_data if order['is_buy_order'] and order['type'] == 2])

您可以通过执行regionC = regionA + regionB来连接字典。

然后,您可以应用以下内容:

 type_1 = max((x for x in regionC if x['is_buy_order'] and x['type'] == 1), key=lambda x: x['price'])
print(type_1)
 type_2 = max((x for x in regionC if x['is_buy_order'] and x['type'] == 2), key=lambda x: x['price'])
print(type_2)

output 将是:

{'is_buy_order': True, 'price': 1000, 'type': 1}
{'is_buy_order': True, 'price': 1000, 'type': 2}

如果您不想考虑type ,则可以将其从列表推导中删除。 那么,就会

 type_1 = max((x for x in regionC if x['is_buy_order']), key=lambda x: x['price'])

您可以先加入列表:

max([d for d in regionA + regionB if  d['is_buy_order']], key=lambda d: d['price']))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM