按最近日期python从另一个字典列表更新字典列表

时间:2018-01-20 05:37:23

标签: python dictionary

有两个python词典列表

buy_lists = [{"buy_date":"2017-01-02","buy_price":10.50},
{"buy_date":"2017-01-15","buy_price":11.25},
{"buy_date":"2017-02-01","buy_price":8.50},
{"buy_date":"2017-02-04","buy_price":12.50}]

sell_lists=[{"sell_date":"2017-01-02","sell_price":10.50},
    {"sell_date":"2017-01-03","sell_price":10.75},
    {"sell_date":"2017-01-04","sell_price":12.50},
    {"sell_date":"2017-01-10","sell_price":11.00},
    {"sell_date":"2017-01-25","sell_price":11.25},
    {"sell_date":"2017-01-27","sell_price":11.75},
    {"sell_date":"2017-01-30","sell_price":7.50},
    {"sell_date":"2017-02-01","sell_price":8.50},
    {"sell_date":"2017-02-11","sell_price":9.50},
    {"sell_date":"2017-02-15","sell_price":14.50},
    {"sell_date":"2017-02-04","sell_price":12.50},
    {"sell_date":"2017-02-05","sell_price":12.75},
    {"sell_date":"2017-02-06","sell_price":12.80}]

如何选择sell_listsbuy_lists项目最近的日期,并更新buy_lists

buy_lists=[{"buy_date":"2017-01-02","buy_price":10.50,"sell_date":"2017-01-03","sell_price":10.75},
{"buy_date":"2017-01-15","buy_price":11.25,"sell_date":"2017-01-27","sell_price":11.75},
{"buy_date":"2017-02-01","buy_price":8.50,"sell_date":"2017-02-11","sell_price":9.50},
{"buy_date":"2017-02-04","buy_price":12.50,"sell_date":"2017-02-05","sell_price":12.75}]

这是我现在的代码。

for x in buy_lists:
    for y in sell_lists:
        # check if the x["buy_date"] is the most closest date after this date
        # Then y add to x

2 个答案:

答案 0 :(得分:1)

按日期对列表进行排序;迭代销售清单;如果您发现日期大于当前购买日期,请更新购买;得到下一个购买,继续。

import datetime    
def f(d):
    try:
        s = d['buy_date']
    except KeyError as e:
        s = d['sell_date']
    return datetime.datetime.strptime(s, '%Y-%m-%d')

buy_lists.sort(key=f)
sell_lists.sort(key=f)

bl = iter(buy_lists)
try:
    buy = next(bl)
    for sell in sell_lists:
        if f(sell) > f(buy):
            print(buy, sell)
            buy.update(sell)
            buy = next(bl)
except StopIteration:
    pass

如果同一天有多次购买,它可能无法生成您想要的产品。

答案 1 :(得分:0)

当迭代列表时,您可以最小化两个日期之间的正差异。

from dateutil import parser

def day_diff(buy, sell):
    x = parser.parse(buy)
    y = parser.parse(sell)
    return (y-x).days

sd = 'sell_date'  # shortens code
for d1 in buy_lists:
    buy = d1.get('buy_date')
    best_match = min(sell_lists, 
        key=lambda x: day_diff(buy, x.get(sd)) if day_diff(buy, x.get(sd))>=0 else 10**8)
    d1.update(best_match)

buy_lists
# returns:
[{'buy_date': '2017-01-02', 'buy_price': 10.5,
  'sell_date': '2017-01-02', 'sell_price': 10.5},
 {'buy_date': '2017-01-15', 'buy_price': 11.25, 
  'sell_date': '2017-01-25', 'sell_price': 11.25},
 {'buy_date': '2017-02-01', 'buy_price': 8.5,
  'sell_date': '2017-02-01', 'sell_price': 8.5},
 {'buy_date': '2017-02-04', 'buy_price': 12.5,
  'sell_date': '2017-02-04', 'sell_price': 12.5}]