比较Python中的关键内容

时间:2016-02-18 07:10:55

标签: python dictionary key

假设我有两个带相同键的词典

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 

3 个答案:

答案 0 :(得分:1)

你可以这样做,

>>> dict1 = {'a': 1, 'b':2 , 'c': 3}
>>> dict2 = {'a': 1, 'b':2 , 'c': 4}
>>> {dict1[i] for i in dict1 if dict1[i]==dict2[i]}
set([1, 2])

答案 1 :(得分:1)

试试这个:

set(dict1.values()) & set(dict2.values())

https://docs.python.org/3.5/library/stdtypes.html#set.intersection

答案 2 :(得分:0)

这是你想要的吗?

dict1 = {a: 1, b:2 , c: 3}
dict2 = {a: 1, b:2 , c: 4}

common = []
for key, value in dict1.items():
    if dict2[key] == value:
        common.append(value)

intersection = set(common)
print intersection