Python:将元组列表按指定条件转换为字典
Solution to Convert Tuple List to Target Dictionary with Latest 'End' Record
Here's a straightforward, readable solution to transform your list of tuples into the desired dictionary, including logic to retain only the latest 'End' entry for each book:
# Sample input list Book = [ (24, '2008-10-30', 'Start'), (24, '2008-12-20', 'End', 'sold'), (24, '2009-02-04', 'End', 'sold'), (24, '2009-11-25', 'End', 'sold'), (25, '2009-01-01', 'Start'), (25, '2009-11-14', 'End', 'returned'), (26, '2010-04-03', 'Start'), (26, '2010-10-11', 'End', 'sold') ] # Initialize empty result dictionary bookDict = {} for item in Book: book_id = item[0] date = item[1] status = item[2] # Create a blank entry for the book if it doesn't exist yet if book_id not in bookDict: bookDict[book_id] = {} if status == 'Start': # Assign the start date (assumes one Start entry per book; overwrites if multiple exist) bookDict[book_id]['Start'] = date elif status == 'End': reason = item[3] # Only update if no End exists yet, or current date is later than stored date # (YYYY-MM-DD strings can be compared directly for chronological order) if 'End' not in bookDict[book_id] or date > bookDict[book_id]['End']: bookDict[book_id]['End'] = date bookDict[book_id]['reason'] = reason # Print the final result print(bookDict)
Key Logic Explanations:
- Initialization: We start with an empty dictionary to build our result.
- Book Entry Setup: For each tuple, we first ensure the book ID has an entry in the dictionary to avoid
KeyError. - Start Record Handling: Directly assign the start date to the book's entry (works even if multiple Start entries exist, though it will use the last one encountered).
- End Record Handling: We check if there's no existing End date, or if the current End date is later than the stored one. Since dates are in
YYYY-MM-DDformat, string comparison works perfectly for chronological ordering. We update both the End date and reason whenever we find a newer End record.
Output Result:
When you run the code, you'll get exactly the structure you need:
{ 24: {'Start': '2008-10-30', 'End': '2009-11-25', 'reason': 'sold'}, 25: {'Start': '2009-01-01', 'End': '2009-11-14', 'reason': 'returned'}, 26: {'Start': '2010-04-03', 'End': '2010-10-11', 'reason': 'sold'} }
内容的提问来源于stack exchange,提问作者MahsaAzizi
相关产品推荐
相关产品推荐

