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

基于CSV生成三个Python字典,实现值的集合交集运算

Got it, let's walk through how to build those three dictionaries from a single CSV file—with the first one using sets specifically for easy intersection operations. I'll break this down with clear definitions, examples, and working code:

1. First Dictionary Definition

This dictionary maps a primary category (e.g., product category, group) to a set of related items. Using a set is critical here because sets natively support efficient intersection operations, which we'll leverage later to create the third dictionary.

Example CSV Input

Suppose our CSV (data.csv) looks like this:

category,item,tag
fruit,apple,red
fruit,banana,yellow
fruit,orange,orange
veggie,carrot,orange
veggie,banana,yellow

Resulting dict1

dict1 = {
    'fruit': {'apple', 'banana', 'orange'},
    'veggie': {'carrot', 'banana'}
}

Key note: Sets automatically handle duplicates, so even if an item appears multiple times in the CSV for the same category, it only gets stored once—ideal for our intersection use case.

2. Second Dictionary Definition

This dictionary uses a secondary dimension from the CSV (in our example, tag) to map to its own set of items. The structure mirrors dict1 but uses a different key type.

Resulting dict2

dict2 = {
    'red': {'apple'},
    'yellow': {'banana'},
    'orange': {'orange', 'carrot'}
}
3. Example of dict3 (Intersection-Based Dictionary)

dict3 is built by calculating the intersection of values from dict1 and dict2 for every possible pair of keys. In short, it answers: "Which items are in both [category X] and [tag Y]?"

Resulting dict3

dict3 = {
    ('fruit', 'red'): {'apple'},
    ('fruit', 'yellow'): {'banana'},
    ('fruit', 'orange'): {'orange'},
    ('veggie', 'red'): set(),  # No overlapping items
    ('veggie', 'yellow'): {'banana'},
    ('veggie', 'orange'): {'carrot'}
}

Core logic: For each combination of a category (from dict1) and a tag (from dict2), we compute the intersection of their item sets. If there's no overlap, the value is an empty set.

Full Working Code

Here's how to generate all three dictionaries from the CSV using Python's built-in csv module:

import csv

# Initialize empty dictionaries
dict1 = {}  # category -> set of items
dict2 = {}  # tag -> set of items
dict3 = {}

# Read and process the CSV
with open('data.csv', 'r') as csv_file:
    reader = csv.DictReader(csv_file)
    for row in reader:
        category = row['category'].strip()
        item = row['item'].strip()
        tag = row['tag'].strip()
        
        # Populate dict1 with sets
        if category not in dict1:
            dict1[category] = set()
        dict1[category].add(item)
        
        # Populate dict2 with sets
        if tag not in dict2:
            dict2[tag] = set()
        dict2[tag].add(item)

# Build dict3 by computing intersections
for cat_key, cat_items in dict1.items():
    for tag_key, tag_items in dict2.items():
        dict3[(cat_key, tag_key)] = cat_items.intersection(tag_items)

# Print results to verify
print("=== dict1 ===")
for k, v in dict1.items():
    print(f"{k}: {v}")

print("\n=== dict2 ===")
for k, v in dict2.items():
    print(f"{k}: {v}")

print("\n=== dict3 ===")
for k, v in dict3.items():
    print(f"{k}: {v}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:11:32