You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于日期维度字典生成新字典?请求技术指导

Transforming Your Date-Wise Dictionary into Other Structures

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:29:36