czach123
czach123

Reputation: 29

How to compare two lists in the same dictionary and see if a value is in both

I am fairly new to Python and would appreciate some help for a project I am working on for work.
I have a dictionary of lists and want to traverse the dictionary and check if any values of the lists are the same.

dict={'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}

I need to check the list value of 'one' and check to see if in 'two' and 'three', then check 'two' values are in 'three' and so on. Then I need to print out the key and values that are the same. ie.

3 - 'one' 'two'
5 - 'two' 'three'

Not sure the best way to do this.

Upvotes: 0

Views: 442

Answers (5)

Moses Koledoye
Moses Koledoye

Reputation: 78556

You can take the combination of keys using itertools.combinations and find the itersection of values for pairwise keys:

from itertools import combinations

dct = {'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}

for k1, k2 in combinations(dct, 2):
    s = set(dct[k1]).intersection(dct[k2])
    for x in s:
        print("{2} - '{0}' '{1}'".format(k1, k2, x))

3 - 'one' 'two'
5 - 'two' 'three'

Upvotes: 4

AGN Gazer
AGN Gazer

Reputation: 8378

for v in set(sum(dict.values(), [])):
    keys = [k for k in dict if v in dict[k]]
    print("{:d} - {:s}".format(v, "'" + "' '".join(keys) + "'"))

Upvotes: 0

quizdog
quizdog

Reputation: 662

You can turn the dictionary into a list of tuples then iteratively compare the first tuple in the list to the remaining tuples in the list like this:

data = {'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}

search = list(data.items())

while search:
    target = search.pop(0)
    for candidate in search:
         for item in target[1]:
            if item in candidate[1]:
                 print (item, target[0], candidate[0])
3 one two
5 two three        

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113978

new_data = {}
data_dict = {'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}

for key,values in data_dict.items():
   for value in values:
        new_data.setdefault(value,[]).append(key)

print new_data

I guess is how i would do it... theres trickier and cooler ways but this is simple to understand and i think the smallest big-O

Upvotes: 0

Jason
Jason

Reputation: 93

A nice way to do it in pure python is to iterate over all possible values in the resulting lists. Create a dictionary that maps each value to the keys associated with it.

d ={'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}

results = dict()

for key in d.keys():
    for value in d[key]:
        if value in results:
            results[value].append(key)
        else:
            results[value] = [key]

Now, when you call results, you will get a dictionary that looks like

{1: ['one'],
 2: ['one'],
 3: ['two', 'one'],
 4: ['two'],
 5: ['three', 'two'],
 6: ['three'],
 7: ['three']}

We can then go through the results and only print out the ones with multiple associated keys.

for number, strings in results.items():
    if len(strings) > 1:
        print number, strings

Giving you:

3 ['two', 'one']
5 ['three', 'two']

This way of doing it should be fast since it's linear with respect to the total length of the combined lists from the original dictionary.

Upvotes: 1

Related Questions