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

Python 3字典合并及列表元素添加、多地点员工工时合并需求

Alright, let's walk through these two Python 3 tasks step by step—both are common data wrangling scenarios, so I'll share practical, easy-to-follow code for each.

Solution for Two Python 3 Tasks

Task 1: Merge Dictionaries & Combine List Values for Shared Keys

Suppose you have two dictionaries where some keys map to lists, and you want to merge them: for keys that exist in both, you'll append the list elements together; for unique keys, you just keep their original values. Here's a straightforward approach:

Example Code

dict_a = {"fruits": ["apple", "banana"], "vegetables": ["carrot"]}
dict_b = {"fruits": ["orange"], "grains": ["rice", "wheat"]}

# Initialize our merged dictionary
merged_dict = {}

# Grab all unique keys from both dictionaries
all_keys = set(dict_a.keys()).union(set(dict_b.keys()))

for key in all_keys:
    # Collect values from both dicts (if they exist)
    combined_values = []
    if key in dict_a:
        combined_values.extend(dict_a[key])
    if key in dict_b:
        combined_values.extend(dict_b[key])
    merged_dict[key] = combined_values

print(merged_dict)
# Output: {'fruits': ['apple', 'banana', 'orange'], 'vegetables': ['carrot'], 'grains': ['rice', 'wheat']}

If you prefer a more concise method using collections.defaultdict, this works too:

from collections import defaultdict

merged_dict = defaultdict(list)
for d in [dict_a, dict_b]:
    for key, val_list in d.items():
        merged_dict[key].extend(val_list)

# Convert back to a regular dictionary if needed
merged_dict = dict(merged_dict)

Task 2: Merge Cross-Location Employee Hours Data

For this task, we need to combine time entries for employees who appear in multiple locations, summing their daily hours (I'll also include tracking all locations they worked at, since that's useful context). Let's start with sample data, then build the solution.

Sample Input Data

employee_times = [
    {"LOCATION": "NYC", "NAME": "name_1", "MON": 8, "TUES": 7, "WED": 8, "THURS": 8, "FRI": 7},
    {"LOCATION": "LA", "NAME": "name_1", "MON": 6, "TUES": 8, "WED": 7, "THURS": 8, "FRI": 8},
    {"LOCATION": "CHI", "NAME": "name_2", "MON": 8, "TUES": 8, "WED": 8, "THURS": 8, "FRI": 8}
]

Solution Code

merged_employees = {}

for entry in employee_times:
    name = entry["NAME"]
    # If the employee isn't in our merged dict yet, add them with initial data
    if name not in merged_employees:
        merged_entry = entry.copy()
        # Store locations as a list to track all work sites
        merged_entry["LOCATION"] = [entry["LOCATION"]]
        merged_employees[name] = merged_entry
    else:
        # Sum up daily hours for the existing employee entry
        merged_entry = merged_employees[name]
        merged_entry["MON"] += entry["MON"]
        merged_entry["TUES"] += entry["TUES"]
        merged_entry["WED"] += entry["WED"]
        merged_entry["THURS"] += entry["THURS"]
        merged_entry["FRI"] += entry["FRI"]
        # Add the new location to their list
        merged_entry["LOCATION"].append(entry["LOCATION"])

# Convert the dictionary values to a list if you want a clean output format
result_list = list(merged_employees.values())

# Print the final merged data
for emp in result_list:
    print(emp)

Output

{'LOCATION': ['NYC', 'LA'], 'NAME': 'name_1', 'MON': 14, 'TUES': 15, 'WED': 15, 'THURS': 16, 'FRI': 15}
{'LOCATION': ['CHI'], 'NAME': 'name_2', 'MON': 8, 'TUES': 8, 'WED': 8, 'THURS': 8, 'FRI': 8}

If you don't need to track all locations, just remove the parts that handle the LOCATION list—focus solely on summing the daily hours.

内容的提问来源于stack exchange,提问作者Cesar Rodriguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:53:14