so I have a dict :
JavaScript
x
6
1
marker_dict[experiment_id] = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
2
'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : ,'qualityStatus' : 'A' },
3
'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
4
'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': , 'positionCm' : 80,'qualityStatus' : 'B' },
5
'SM0080BQ': { 'chromosome' : , 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}
6
I want to sort my dict on ‘i.chromosome’, ‘i.linkageGroup’ and ‘i.positionCm’
What I am doing :
JavaScript
1
2
1
marker_list = sorted(marker_dict[experiment_id].values(), key=lambda i: (i.chromosome, i.linkageGroup, i.positionCm))
2
And i got :
JavaScript
1
2
1
TypeError: '<' not supported between instances of 'Nonetype' and 'int'
2
In python 2, they were doing :
JavaScript
1
2
1
markerList=sorted(markerDic.values(), key=operator.attrgetter('chromosome','linkageGroup','positionCm'))
2
Could you help me please, I am lost !
Advertisement
Answer
Given
JavaScript
1
6
1
t = {'SM0012AQ': { 'chromosome' : 1, 'linkageGroup':8, 'positionCm' : 45,'qualityStatus' : 'A' },
2
'SM0075AQ': { 'chromosome' : 1, 'linkageGroup': 7, 'positionCm' : None ,'qualityStatus' : 'A' },
3
'SM0078BQ': { 'chromosome' : 3, 'linkageGroup': 78, 'positionCm' : 7,'qualityStatus' : 'B' },
4
'SM0079PQ': { 'chromosome' : 4, 'linkageGroup': None, 'positionCm' : 80,'qualityStatus' : 'B' },
5
'SM0080BQ': { 'chromosome' : None, 'linkageGroup': 78, 'positionCm' : 447,'qualityStatus' : 'T' }}
6
and the requirement that None
s are for int
, you can solve it using
JavaScript
1
2
1
dict(sorted(t.items(), key=lambda i: (i[1]['chromosome'] if i[1]['chromosome'] is not None else -1, i[1]['linkageGroup'] if i[1]['linkageGroup'] is not None else -1 , i[1]['positionCm'] if i[1]['positionCm'] is not None else -1)))
2
where I’ve made the assumption that the numbers you have are 0 or positive. If you can also have negatives you need to change the -1 to a very large negative number.
The result:
JavaScript
1
21
21
1
{'SM0080BQ': {'chromosome': None,
2
'linkageGroup': 78,
3
'positionCm': 447,
4
'qualityStatus': 'T'},
5
'SM0075AQ': {'chromosome': 1,
6
'linkageGroup': 7,
7
'positionCm': None,
8
'qualityStatus': 'A'},
9
'SM0012AQ': {'chromosome': 1,
10
'linkageGroup': 8,
11
'positionCm': 45,
12
'qualityStatus': 'A'},
13
'SM0078BQ': {'chromosome': 3,
14
'linkageGroup': 78,
15
'positionCm': 7,
16
'qualityStatus': 'B'},
17
'SM0079PQ': {'chromosome': 4,
18
'linkageGroup': None,
19
'positionCm': 80,
20
'qualityStatus': 'B'}}
21