Reputation: 473
I am trying to prototype business data analysis application in Python 2.7. The code is:
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'}]
It has to get the data from API and print out names of technology companies only. Instead of that I get
Traceback (most recent call last):
File "C:\Users\gniteckm\Desktop\all2.py", line 9, in <module>
print item[{'sector':'technology'}]
TypeError: unhashable type: 'dict'
Upvotes: 0
Views: 739
Reputation: 1124318
You cannot filter dictionaries; they don't take a query. You'll have ta pass in keys that actually exist in the item
dictionaries, and because this is JSON, item
will only have string keys.
You can filter on specific key-value pairs with an if
statement:
for item in data:
if item['sector'] == 'technology':
print item
This assumes that all item
dictionaries in data
have a 'sector'
key. If not, use dict.get()
to return a default if the key is missing:
for item in data:
if item.get('sector') == 'technology':
print item
Upvotes: 1