0

Below code is working in python 2 but its breaking in python 3, could you please help

destObj={('SVC_157', None):'05-04-2022', ('SVC_157', 'V1.0'):'06-07-2022'}

for (rel, ver) in sorted(destObj.keys()):
    print((rel, ver))

Please note: position of None is not fixed, it may vary if release is having more components for ex like below, ('SVC_157', 'SMU', 'Windows 10 ARM64', None )

FYI: Its not duplicate of Sorting list by an attribute that can be None

Yash
  • 1
  • 1
  • The problem is that comparison against `None` in Python 3 throws an exception – Dani Mesejo Jul 29 '22 at 18:08
  • @joanis I found the duplicate and close the question, so I want to avoid any possible conflict of interest – Dani Mesejo Jul 29 '22 at 18:15
  • But reading the duplicate, it's not a perfect duplicate. If OP is not a reasonably advanced Python programmer, they might not know how to apply that solution to a tuple that might contain None, rather than to elements that might be None themselves. Maybe put the lambda expression from your deleted answer in a comment here? – joanis Jul 29 '22 at 18:19
  • I've already seen that post, I know it seems similar but its different – Yash Jul 29 '22 at 18:24

1 Answers1

0

Use the key parameter as below, to mimic the Python 2 behavior:

destObj = {('SVC_157', None): '05-04-2022', ('SVC_157', 'V1.0'): '06-07-2022'}

def key(t):
    return tuple(e or "" for e in t)

for (rel, ver) in sorted(destObj.keys(), key=key):
    print((rel, ver))

Output

('SVC_157', None)
('SVC_157', 'V1.0')

If you have tuples of multiple sizes, the unpacking in the for loop is not going to work, do the following instead:

destObj = {('SVC_157', 'SMU', 'Windows 10 ARM64', None): '05-04-2022', ('SVC_157', 'V1.0'): '06-07-2022'}

def key(t):
    return tuple(e or "" for e in t)

for tup in sorted(destObj.keys(), key=key):
    print(tup)
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76