如何基于日期维度字典生成新字典?请求技术指导
Hey there! Let's walk through how to transform your date_wise_data dictionary into other useful structures—since you didn't specify exactly what end result you need, I'll cover a few common, practical scenarios you might be aiming for.
1. User-Wise Date-Value Mapping (Transposed Structure)
If you want to flip the structure so each user is the top-level key, with their values mapped to each date, here's how to do it:
date_wise_data = { '2018-04-09': {'user1': 3, 'user2': 1, 'user3': 1, 'user4': 1}, '2018-04-08': {'user1': 2, 'user2': 0, 'user3': 1, 'user4': 1}, '2018-04-07': {'user1': 6, 'user2': 5, 'user3': 1, 'user4': 2}, '2018-04-06': {'user1': 2, 'user2': 0, 'user3': 1, 'user4': 1}, '2018-04-05': {'user1': 2, 'user2': 0, 'user3': 2, 'user4': 8}, '2018-04-04': {'user1': 0, 'user2': 0, 'user3': 5, 'user4': 1} } # Initialize empty dict for user-focused data user_wise_data = {} for date, user_values in date_wise_data.items(): for user, value in user_values.items(): # Create entry for user if they don't exist yet if user not in user_wise_data: user_wise_data[user] = {} # Assign the value to the user's date entry user_wise_data[user][date] = value # Example output snippet: {'user1': {'2018-04-09': 3, '2018-04-08': 2, ...}, ...}
2. Total Values Per User
If you just need a summary of each user's total across all dates, use this concise approach:
user_totals = {} for date, user_values in date_wise_data.items(): for user, value in user_values.items(): # Add to existing total or start at 0 if user is new user_totals[user] = user_totals.get(user, 0) + value # Output will be: {'user1': 15, 'user2': 6, 'user3': 11, 'user4': 14}
3. Total Values Per Date
If you want to calculate the sum of all user values for each date, a dictionary comprehension makes this quick:
date_totals = {date: sum(user_values.values()) for date, user_values in date_wise_data.items()} # Output snippet: {'2018-04-09': 6, '2018-04-08': 4, ...}
If you had a specific transformation in mind (like filtering certain users, sorting dates, or something else), just share more details and I can adjust this further!
内容的提问来源于stack exchange,提问作者Sreenath

