Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – list of lists – check if unique combination of values has last different value in the list

we have a list of lists

links_list = [['project1','repo1', 'folder1', 'target1', 'link1', 'branch1'], 
             ['project1', 'repo1', 'folder1', 'target1', 'link1', 'branch1'], 
             ['project1', 'repo1', 'folder1', 'target1', 'link1', 'branch2'],
             ['project2', 'repo2', 'folder2', 'target2', 'link2', 'branch2']]

for link_list in links_list:
    print(link_list)

Our unique combination of columns are: project, repo, folder and target

That means, it is OK if we have lists which are repeated such as the first two lists:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['project1', 'repo1', 'folder1', 'target1', 'link1', 'branch1'], 
['project1', 'repo1', 'folder1', 'target1', 'link1', 'branch1']

That is not an issue.

it is NOT OK if BRANCH column (the last column) is different for this combination of the first 4 columns: project, repo, folder and target.

So since we have

['project1', 'repo1', 'folder1', 'target1', 'link1', 'branch1'] and

['project1', 'repo1', 'folder1', 'target1', 'link1', 'branch2']
we do not know which BRANCH value is valid so script should exit and throw exception for this use case because for combination:
‘project1’, ‘repo1’, ‘folder1’, ‘target1’ we have two branches: branch1 and branch2 which makes inconsistency.

Link column (column5 – index4) is irrelevant for the logic.

I am really not sure how to start here.

Thanks a lot

>Solution :

combos = {}
for link_list in links_list:
  key = tuple(link_list[:4])
  branch = link_list[5]
  if combos.setdefault(key, branch) != branch:
    raise Exception(f"{key} already has branch '{combos[key]}'.")

You can use setdefault to set and/or retrieve the existing key.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading