2
$\begingroup$
dict1 = {'chr1:1000-2000': ['A', 'B', 'C'], 'chr2:999-2000': ['A', 'X', 'Y'], 'chr3:1200-3000': ['B', 'A', 'C']}

list1 = [('A', 'B'), ('A', 'C'), ('A', 'X'), ('A', 'Y'), ('B', 'C'), ('B', 'X'), ('B', 'Y'), ('C', 'X'), ('C', 'Y'), ('X', 'Y')]

I want to map the items in list1 eg('A','B') both in dict1 values and return keys in wich this group occur

$\endgroup$
2
  • 1
    $\begingroup$ Please edit your question and show us the expected output. Should both keys be there or is one enough? Can they be in any order? $\endgroup$
    – terdon
    Nov 16, 2021 at 17:51
  • $\begingroup$ edited thank you $\endgroup$
    – amardeep
    Sep 20, 2023 at 9:02

1 Answer 1

1
$\begingroup$

I am assuming you only want keys where both tuple items are present. If so, this should work:

no_match = []
for item in list1:
    item1, item2 = item
    wanted_keys = [
        key for key in dict1.keys() if
        item1 in dict1[key] and
        item2 in dict1[key]
    ]
    if len(wanted_keys) > 0:
        print("%s:  %s" % (item, wanted_keys))
    else:
        no_match.append(item)
print("No matches found for items:", no_match)

The output looks like this:

('A', 'B'):  ['chr1:1000-2000', 'chr3:1200-3000']
('A', 'C'):  ['chr1:1000-2000', 'chr3:1200-3000']
('A', 'X'):  ['chr2:999-2000']
('A', 'Y'):  ['chr2:999-2000']
('B', 'C'):  ['chr1:1000-2000', 'chr3:1200-3000']
('X', 'Y'):  ['chr2:999-2000']
No matches found for items: [('B', 'X'), ('B', 'Y'), ('C', 'X'), ('C', 'Y')]

There is probably a better, more elegant way of doing this, I am not a python person, but this is the best I could come up with.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.