MST

星途 面试题库

面试题:Python中字典与集合交集并集操作基础

假设有一个字典`dict1 = {'a': 1, 'b': 2, 'c': 3}`和一个集合`set1 = {'a', 'c', 'd'}`,请编写Python代码实现获取字典键与集合的交集,并输出结果。如果字典的值是列表,例如`dict2 = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}`,集合为`set2 = {'a', 'c', 'd'}`,如何获取字典键与集合的交集,并将对应字典值中的元素求和输出。
25.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
# 对于dict1和set1
dict1 = {'a': 1, 'b': 2, 'c': 3}
set1 = {'a', 'c', 'd'}
intersection1 = set(dict1.keys()) & set1
print(intersection1)

# 对于dict2和set2
dict2 = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}
set2 = {'a', 'c', 'd'}
intersection2 = set(dict2.keys()) & set2
result = 0
for key in intersection2:
    result += sum(dict2[key])
print(result)