Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare lists in the same dictionary of lists

In resume, I have two keys in the same dictionary where each one has their corresponding lists.

I try to compare both list to check common and differential elements. It means that the output I will count how many elements are identical or present in only one key's list.

from the beginning I am inserting the elements using the files as arguments and they are read in the function

def shared(list):
        dict_shared = {}
        for i in list:
                infile = open(i, 'r')
                if i not in dict_shared:
                        dict_shared[i] = []

                for line in infile:
                        dict_shared[spacer].append(record.id)

        return dict_shared

Now I am stuck trying to find a way to compare the lists created and present in the dictionary.

dict = {a:[1,2,3,4,5], b:[2,3,4,6]}

My intention is to compare the lists in order to have the lines shared between two texts.

a: [1,5]
b: [6]
a-b: [2,3,4]

From now I can't find a way to solve this. Any suggestion?

like image 471
F.Lira Avatar asked Apr 16 '20 13:04

F.Lira


People also ask

How do you compare two lists the same?

A straightforward way to check the equality of the two lists in Python is by using the equality == operator. When the equality == is used on the list type in Python, it returns True if the lists are equal and False if they are not.

Can you compare lists with ==?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

Can two dictionaries be compared?

When I had to compare two dictionaries for the first time, I struggled―a lot! For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.


Video Answer


2 Answers

You could use set:

d = {'a':[1,2,3,4,5], 'b':[2,3,4,6]}
print(list(set(d['a'])-set(d['b'])))
print(list(set(d['b'])-set(d['a'])))
print(list(set(d['b'])&set(d['a'])))

result:

[1, 5]
[6]
[2, 3, 4]
like image 104
jizhihaoSAMA Avatar answered Oct 20 '22 18:10

jizhihaoSAMA


you can do that by utilising python inbuilt functions like union, difference, intersection. Note: These are for sets, you can convert a list to set by

1stset = set(a)

example:

print(1stset.difference(2ndset))

print(1stset.intersection(2ndset))

print(1stset.union(2ndset))

you can refer the following links for more information

https://www.geeksforgeeks.org/python-intersection-two-lists/

https://www.geeksforgeeks.org/python-union-two-lists/

https://www.geeksforgeeks.org/python-difference-two-lists/

like image 29
Lavanya V Avatar answered Oct 20 '22 17:10

Lavanya V