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?
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.
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.
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.
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]
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With