【发布时间】:2016-02-18 07:10:55
【问题描述】:
假设我有两个具有相同键的字典
dict1 = {first_letter: a, second_letter:b , third_letter: c}
dict2 = {first_letter: a, second_letter:b , third_letter: d}
我有相同的键,但我想比较键内的内容并打印交叉点
所以如果有另一个字典叫做
intersection = {}
我想要结果
print intersection
{a,b}
我有两个文件中的两个字典,我只想将两个文件的交集放在另一个文件中。因此,如果键包含相同的值,则将其存储到另一个文件中并打印出来。
这是我的代码:
keys = ['lastname', 'firstname', 'email', 'id', 'phone']
dicts = []
second_dicts = []
third_dicts = []
intersection = []
with open("oldFile.txt") as f:
for line in f:
# Split each line.
line = line.strip().split()
# Create dict for each row.
d = dict(zip(keys, line))
# Print the row dict
print d
# Store for future use
dicts.append(d)
print "\n\n"
with open ("newFile.txt") as n:
for line in n:
# Split each line.
line = line.strip().split()
# Create dict for each row.
r = dict(zip(keys, line))
# Print the row dict
print r
# Store for future use
second_dicts.append(r)
print"\n\n"
#shared_items = set(dicts.items()) & set(second_dicts.items())
#print shared_items
#if oldFile has the same content as newFile then make a a newFile
#called intersectionFile and print
【问题讨论】:
-
交集不是字典。
-
你需要澄清“交叉点”。如果
d1 = {'a': 1, 'b': 2}和d2 = {'a': 2, 'b': 1},它们的交集是什么?如果是{1, 2},@mirosval 的答案是正确的。如果是空集,@AvinashRaj 是正确的。 -
但我得到错误打印 set(dicts.values()) & set(second_dicts.values()) AttributeError: 'list' object has no attribute 'values'
标签: python dictionary key