2014-11-19 2 views
1

파이썬에서 개체 사전을 정렬하려고합니다. 이 객체에는 속성이 있습니다.이 객체를 "아키텍처"라고 부릅시다. 그래서, 내 사전을 정렬하려면 :개체 사전을 not-always-there 특성으로 정렬하십시오.

data.sort(key=attrgetter('architecture')) 

지금까지 너무 좋아.

하지만 일부 개체는 '아키텍처'(때때로 예, 때로는 아니요) 속성을 가질 수 없으며 Python 콘솔은 AttributeError 예외를 발생시킵니다.

내 질문은 개체의 일부가 정렬 할 특성이 없을 때 개체 사전을 특성별로 정렬 할 수 있다는 것입니다.

+0

함께 사용하려는 샘플 사전을 추가 할 수 있습니까? –

+3

먼저 속성이없는 사람들을 어떻게 정렬 하시겠습니까? 마지막? 제외 되었습니까? 당신은'hasattr '을 테스트하고 어떤 디폴트 ('None'?)를 사용할 수 있습니다. – jonrsharpe

+0

if/else, try/except 블록을 사용합니까? – kezzos

답변

0

마지막으로 속성이없는 항목을 넣고 싶다고 가정 해 보겠습니다.

from operator import attrgetter 

data_with_attr = list(d for d in data.values() if hasattr(d, 'architecture')) 
data_with_attr.sort(key=itemgetter('architecture')) 
data_with_attr += list(d for d in data.values() if not hasattr(d, 'architecture')) 

나는 object dictionary을 올바르게 이해하고 있습니다.

0

개체가 속성을 가지고 있으며, 사용하는 경우 검사는 속성이없는 개체를 원하는 위치에 따라 float("inf") 또는 float("-inf") 정렬 될에 : 당신은 키와 값을 사용 항목을 원하는 경우

srt = sorted(d,key=lambda x: d[x].architecture if hasattr(d[x], "architecture") else float("inf")) 

:

srt= (sorted(d.items(),key=lambda x: x[1].architecture if hasattr(x[1], "architecture") else float("inf"))) 

dicts 난 그냥 언급하지 수,

0

내가 싫어 .sort 방법이 없습니다 ...

어떻게 사전을 정렬 하시겠습니까? 사전은 해시를 사용하여 키에 액세스하므로 반복 할 때 순서는 해시 키에 따라 다르며 키는 다릅니다. 따라서 사전은 정렬을 제공하지 않습니다.

그러나 원래의 질문에 대한 (지금의 (key, value) -list에이 프로젝트) 이것에 대해 무엇을 :

ndata = sorted((tpl for tpl in data if hasattr(tpl[0], 'architecture')), 
       key=lambda x: getattr(tpl[0], 'architecture')) 
# if you want to add those entries, not having 'architecture': 
ndata += list(set(data) - set(ndata)) 

당신에 대한 질문은 지금 : 당신이 그 항목을하지 무엇을 하시겠습니까? contentaling a 'architecture' -field.

관련 문제