1

I have a nested list

test_list = [['AA', 'OFF'], ['BB', 'OFF'], ['BB', 'ON'], ['BB', 'ON'], ['CC', 'OFF'], ['DD', 'OFF'], ['EE', 'OFF']]

I would like to find matching index 0 sub-elements such as

['BB', 'OFF'], ['BB', 'ON'], ['BB', 'ON']

and filter out any sub-items with 'OFF' in index 1 as long as there is a matching index 0 with ' ON' found and not keep duplicates, otherwise just keep the sub-elements.

So for the above example, the end result would be:

[['AA', 'OFF'], ['BB', 'ON'], ['CC', 'OFF'], ['DD', 'OFF'], ['EE', 'OFF']]

I tried converting the above to a dictionary but the result changes depending on the chronological order of the list:

test_dict = dict(test_list)
test_dict

output:

{'AA': 'OFF', 'BB': 'ON', 'CC': 'OFF', 'DD': 'OFF', 'EE': 'OFF'} 

Which is exactly what I want

BUT for

test_list1 = [['AA', 'OFF'],['BB', 'ON'],['BB', 'OFF'],['CC', 'OFF'],['DD', 'OFF'],['EE', 'OFF']]
test_dict1 = dict(test_list1)

test_dict1
{'AA': 'OFF', 'BB': 'OFF', 'CC': 'OFF', 'DD': 'OFF', 'EE': 'OFF'}

Which neglects ['BB', 'ON'] because of its position and is not fitting to what I want.

The order of the test_table list doesn't really matter as long as the end values are unique and meet the 'ON' / 'OFF' criteria above. I guess I am looking for a way to group and sort the nested list so that I can then turn it into a dictionary and output the desired result?

2
  • what happens when you have two OFF and one ON like this ['BB', 'OFF'], ['BB', 'OFF'], ['BB', 'ON'],, would you want ON or OFF ? Commented Jan 25, 2021 at 6:15
  • If ON is in the list then it has to be the one displayed and OFF should be dropped. Commented Jan 25, 2021 at 7:51

1 Answer 1

2

You can simply sort the list on the second element of the sub-lists, so that ON always follows OFF with the code:

test_list1 = [['AA', 'OFF'],['BB', 'ON'],['BB', 'OFF'],['CC', 'OFF'],['DD', 'OFF'],['EE', 'OFF']]
test_dict1 = dict(sorted(test_list1, key=lambda x: x[1]))

Results in test_dict1 containing:

{'AA': 'OFF', 'BB': 'ON', 'CC': 'OFF', 'DD': 'OFF', 'EE': 'OFF'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.