Helloimjs0n
Helloimjs0n

Reputation: 67

Comparing key content in Python

Lets say I have two dictionaries with the same keys

dict1 = {first_letter: a, second_letter:b , third_letter: c}

dict2 = {first_letter: a, second_letter:b , third_letter: d}

I have the same keys but I want to compare the content inside of keys and print the intersections

so if there was another dictionary called

intersection = {}

I'd want the results

print intersection

{a,b}

I have the two dictionaries from two files, and I just want to have the intersection of the two files in one other file. So if the keys contain the same value then store it into another file and print it out.

Here is my code:

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 

Upvotes: 1

Views: 72

Answers (3)

Areeb
Areeb

Reputation: 406

This is what you wanted?

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

Upvotes: 0

mirosval
mirosval

Reputation: 6822

Try this:

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

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

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

You may do like this,

>>> 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])

Upvotes: 1

Related Questions