2014-12-03 7 views
0

파이썬 2.7에서 비즈니스 데이터 분석 애플리케이션을 프로토 타입 화하려고합니다. 코드는 다음과 같습니다.API에서 데이터를 가져 오면 TypeError : unhashable type : 'dict'

import urllib2 
import json 

url = 'http://dev.c0l.in:8888' 
api = urllib2.urlopen(url) 
data = json.load(api) 

for item in data: 
    print item[{'sector':'technology'}] 

기술 데이터베이스의 데이터를 가져와야합니다 그 대신에 내가 얻는다

Traceback (most recent call last): 
    File "C:\Users\gniteckm\Desktop\all2.py", line 9, in <module> 
    print item[{'sector':'technology'}] 
TypeError: unhashable type: 'dict' 
+0

'item'은 사전입니다. 너 뭐하려고? JSON 객체 키는 어쨌든 * strings * 일 수 있습니다. –

+0

'dict' 타입은 해쉬 할 수 없으며 인덱스처럼 사용할 수 없습니다.'data'는 어떻게 생겼습니까? – Kasramvd

+0

데이터를 가져 오거나 데이터를 업데이트하려고합니까? –

답변

1

당신은 사전을 여과 할 수 없다. 그들은 쿼리를하지 않습니다. item 사전에 실제로 존재하는 키를 전달해야하며 이는 JSON이기 때문에 item에는 문자열 키만 포함됩니다. 당신은 if 문으로 특정 키 - 값 쌍 필터링 할 수 있습니다

는 :

for item in data: 
    if item['sector'] == 'technology': 
     print item 

data의 모든 item 사전이 'sector' 키를 가지고 있다고 가정합니다. 그렇지 않은 경우 키가 누락 된 경우 기본값을 반환하려면 dict.get()을 사용하십시오.

for item in data: 
    if item.get('sector') == 'technology': 
     print item 
+0

감사합니다! 당신은 내 말 그대로 저장 :) –

관련 문제