How to extract data using json in python - python
I have an issue with a code I've written. When I run the code I get an error :
Traceback (most recent call last):
File "test23_json_users.py", line 23, in <module>
for user_dict in abc['user_account']['sip_id']:
TypeError: list indices must be integers, not str
The code:
result = '[{"user_account":[{"address":null,"name":null,"country":null,"password":"****","extension":"1112","sip_id":"23001#50.50.50.201","sip_name":"23001","user_id":7973712,"locked":false,"created":null,"h323_name":"1101","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1113","sip_id":"23002#50.50.50.201","sip_name":"23002","user_id":8847075,"locked":false,"created":null,"h323_name":"1102","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1114","sip_id":"23003#50.50.50.201","sip_name":"23003","user_id":3680630,"locked":false,"created":null,"h323_name":"1103","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1115","sip_id":"23004#50.50.50.201","sip_name":"23004","user_id":136391,"locked":false,"created":null,"h323_name":"1104","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1116","sip_id":"23005#50.50.50.201","sip_name":"23005","user_id":5692227,"locked":false,"created":null,"h323_name":"1105","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1117","sip_id":"23006#50.50.50.201","sip_name":"23006","user_id":7559026,"locked":false,"created":null,"h323_name":"1106","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1118","sip_id":"23007#50.50.50.201","sip_name":"23007","user_id":3226075,"locked":false,"created":null,"h323_name":"1107","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1119","sip_id":"23008#50.50.50.201","sip_name":"23008","user_id":6184875,"locked":false,"created":null,"h323_name":"1108","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1120","sip_id":"23009#50.50.50.201","sip_name":"23009","user_id":1711112,"locked":false,"created":null,"h323_name":"1109","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1121","sip_id":"23010#50.50.50.201","sip_name":"23010","user_id":5383101,"locked":false,"created":null,"h323_name":"1110","city":null,"email":null,"phone":null,"zip":null}]}'
params = result[result.find('{"'):]
#print params
abc = json.loads(params)
# Here I'm trying to extract just sip_id from the string result using json.
# I am not able to figure out what went wrong .
for user_dict in abc['user_account']['sip_id']:
print 'usersname : %s' % (user_dict['sip_id'])
Change
for user_dict in abc['user_account']['sip_id']:
to
for user_dict in abc['user_account']:
abc['user_account'] is supposed to be a list.
A list a=['hello',1,2,'people'] has 4 elements accessed by indexes a[0] through a[3].
A dictionary d={'a':1,'b':2} has keys and values. In this case d['a'] has value 1, d[b'] has 2.
If you want to access something in abc['user_account'], type abc['user_account'][42]. If you want to iterate over it
for a in abc['user_account']:
print a
Related
How do I get a specific value from a key in a dictionary with multiple values per key?
I have a dictionary in this format: my_dict = {"key1":["value1", "value2", "value3"]} Is there an easy way to get key1's third value? I guess I could get the whole list of values and then split it up, but there must be a better way
You can do a simple look up in the following ways - my_dict['key1'][2] #Output = 'value3' OR (using dict.get) my_dict.get('key1')[2] #Output = 'value3' OR (if you want 3rd element without specifying the key) list(my_dict.values())[0][2] #Output = 'value3' OR (if you want last element without specifying the key) list(my_dict.values())[0][-1] #Output = 'value3'
my_dict['key1'][2] You access the list in. the value like any other list
I prefer to use get i.e. my_dict.get('key1')[2] If you use my_dict['key1'][2] , you will get a KeyError if key1 is not present in my_dict Example - >>> d = {1:3,4:6} >>> d.get(7) # No Error >>> d[7] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 7
How to get values from a list of dictionary?
How to get the values from a list of dictionary?? For example: I want to get the output as 2? data = [{'a':1,'b':2,'c':3}] Below is the error am observing. data['b'] Traceback (most recent call last): File "", line 1, in data['b'] TypeError: list indices must be integers, not str
The dictionary is the first element in data, so you can access it with: data[0]['b'] If you have multiple dictionaries and you aim want to use them in a fallback order, you can use: def obtain_value(list_of_dicts,key): for dict in list_of_dicts: if key in dict: return dict[key] raise KeyError('Could not find key \'%s\''%key) and then call it with obtain_value(data,'b').
converting tuple to dictionary in python
I am trying to convert a line of string to dictionary where i am facing an error. here is what i have and what i did: line="nsd-1:quorum" t=tuple(line.split(":")) d=dict(t) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> d=dict(t) ValueError: dictionary update sequence element #0 has length 5; 2 is required Basically, what i want to achieve is to have a key value pair. So if i have set of values separated by a ":", i want to have it as a key whatever is before the colon and after the colon needs to be the value for the key. example: if i take the above string, i want "nsd-1" as my key and "quorum" as value. Any help is appreciated. Thanks
Wrap it in a list: >>> dict([t]) {'nsd-1': 'quorum'} There's also no need to convert the return value of split to a tuple: >>> dict([line.split(':')]) {'nsd-1': 'quorum'}
Put t inside an empty list, like this: d=dict([t])
Weather Underground API to get historical data in Python
I am trying to pull historical data from the Weather Underground API. I adapted their Python example code (see below). When I run this I get an exception "TypeError: list indices must be integers, not str" The JSON stream includes a bunch of fields with daily summary information (Dailysummary), but I cannot get out and any of the values they have in this list. I put the URL into a JSON viewer to look at the structure, and cannot figure out what I am doing wrong. Any help would be greatly appreciated. import urllib2 import json f = urllib2.urlopen('http://api.wunderground.com/api/d08c4738fb303c66/geolookup/conditions/q/CA/San_Francisco.json') json_string = f.read() parsed_json = json.loads(json_string) location = parsed_json['location']['city'] temp_f = parsed_json['current_observation']['temp_f'] print "Current temperature in %s is: %s" % (location, temp_f) f.close() h = urllib2.urlopen('http://api.wunderground.com/api/d08c4738fb303c66/history_19760508/q/CA/San_Francisco.json') json_string = h.read() parsed_json = json.loads(json_string) date = parsed_json['history']['utcdate']['pretty'] print date print type(parsed_json['history']) snow = parsed_json['history']['dailysummary']['0'] print snow h.close()
It says your problem right in the error: You can't index a list with a string: >>> [1]['0'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not str >>> [1][0] 1 >>> But you do it here: snow = parsed_json['history']['dailysummary']['0'] To fix your problem, make your indexes integers: snow = parsed_json['history']['dailysummary'][0]
I had a similar problem. Since it is a list of length 1, you can access the list item by the index 0. Now, if you check the type of the value item in index 0, it is a dictionary. type(parsed_json['history']['dailysummary'][0]) <type 'dict'> Now, that you know it is a dictionary, you can use keys to access the values. In your case. print parsed_json['history']['dailysummary'][0]['snow'] This give you the value you are looking for. Let me know if this helps.
The way to access the contents in parsed_json dict is using the keys. You can find the keys you're interested in using print parsed_json['history']['dailysummary'].keys() If you do that you'll see that one of the keys is u'snow' which is a unicode string. You can use that string to access the data you're looking for so instead of: parsed_json['history']['dailysummary']['0'] what you need is: parsed_json['history']['dailysummary']['snow']
How do I unpack a list with fewer variables?
k = [u'query_urls', u'"kick"', u'"00"', u'msg=1212', u'id=11'] >>> name, view, id, tokens = k Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack I need to provide 5 variables to unpack this list. Is there a way to unpack with fewer, so that tokens gets the rest of the list. I don't want to write another line to append to a list.... Thanks. Of course I can slice a list, assign individually, etc. But I want to know how to do what I want using the syntax above.
In Python 3 you can do this: (edit: this is called extended iterable unpacking) name, view, id, *tokens = k In Python 2, you will have to do this: (name, view, id), tokens = k[:3], k[3:]