having Key Error while printing json data - python

python 3.5.1
hi i have following json and python code and i want to print json data but it has an error that says:
Key Error : 'A'
python
data = json.load(...)
for item in data['x']
print (item['A'])
json
{"x":[
{"A":"B"},
{"C":"D"}
]}
whats my problem?

To print the values in each dictionary (with unmatching keys), use the values method of the dictionary:
data = json.load(...)
for item in data['x']:
print(item.values())

The problem is that your code assumes that every item in data['x'] will have a key 'A', but as soon as you iterate to a dict that does not have such a key you will get a KeyError.
Try using item.get('A') which will return None (or a default you provide) if there is no key 'A' in your dictionary. It seems like you want to do something like this:
data = json.load(...)
for item in data['x']:
value = item.get('A')
if value:
print(value)
else:
continue
This will print the value associated with the key 'A' if it exists, otherwise it will move on to the next dictionary in the list.

As #elethan pointed the second item would not have key 'A'
You can do the following
data = json.load(...)
for item in data['x']:
print(item.get('A'))
That would not get any error for your specific json input, and print None if it won't find 'A' key in element.
You can also supply default value to .get(), e.g. item.get('A', 'default').
Thanks #elethan

Related

filtering python list/dictionary and retrieve value for selected key

working on Python script. I get a result that is list:
a = [{'S_RAF': {'C_C106': {'D_1103': 'AVE', 'D_1104': '3-AB3242'}}}, {'S_RAF': {'C_C106': {'D_1103': 'OI', 'D_1104': '31503302130'}}}, {'S_RAF': {'C_C106': {'D_1103': 'PQ', 'D_1104': 'IBAN3102495934895'}}}]
And I would like to get the value of Key: D_1104, when the value for key D_1103 is PQ.
what would be best way in python to get the value of this key in element S_RAF/C_C106/{D_1103=PQ}. function should return: IBAN3102495934895.
Thanks
I tried:
a[2]['C_C106']['D_1104']
but is not correct.
Should do it:
a[2]['S_RAF']['C_C106']['D_1104'] # IBAN3102495934895
You can iterate through the list and check the values in each dictionary like this:
for dictionary in a:
if dictionary['S_RAF']['C_C106']['D_1103'] == 'PQ':
iban = dictionary['S_RAF']['C_C106']['D_1104']
Get ISBNs where D_1103 == "PQ".
ibans = [x["S_RAF"]["C_C106"]["D_1104"] for x in a if x["S_RAF"]["C_C106"]["D_1103"]=="PQ"]
ibans = ibans[0] # "IBAN3102495934895"

How can I search for a specific key in a dictionary in Python?

So I got this dictionary from a csv file and I would like to look for a specific key inside this dictionary (actually the og idea was to search for said key in the csv file and then make a dictionary from that key down) but I don't really know how to do it.
So far I got:
df = pd.read_csv('data.csv')
dict = df.to_dict(orient='dict')
for index, line in enumerate(dict):
if "Wavelength [nm]" in line:
print(index)
The idea is to know the index of "Wavelength".
If you want the value of a key without knowing whether it's in the dict, often the most natural way is
value = dict.get( key, defaultvalue)
defaultvalue is what you would set value to in your code once you had established that the key is not present. Often, None, or an empty list or tuple.
If you just waht to check whether the key is present without accessing the value, use
if key in dict:
# do stuff
you can use:
if key in dict:
print(key,dict[key])

I can't get a value from a JSON API response in python

So I am struggling with getting a value from a JSON response. Looking in other post I have managed to write this code but when I try to search for the key (character_id) that I want in the dictionary python says that the key doesn't exist. My solution consists in getting the JSON object from the response, converting it into a string with json.dumps() and the converting it into a dictionary with json.loads(). Then I try to get 'character_id' from the dictionary but it doesn't exist. I am guessing it is related with the format of the dictionary but I have little to none experience in python. The code that makes the query and tries to get the values is this: (dataRequest is a fuction that makes the request and return the response from the api)
characterName = sys.argv[1];
response = dataRequest('http://census.daybreakgames.com/s:888/get/ps2:v2/character/?name.first_lower=' + characterName + '&c:show=character_id')
jsonString = json.dumps(response.json())
print(jsonString)
dic = json.loads(jsonString)
print(dic)
if 'character_id' in dic:
print(dic['character_id'])
The output of the code is:
{"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
{'character_list': [{'character_id': '5428662532301799649'}], 'returned': 1}
Welcome #Prieto! From what I can see, you probably don't need to serialize/de-serialize the JSON -- response.json() returns a python dictionary object already.
The issue is that you are looking for the 'character_id' key at the top-level of the dictionary, when it seems to be embedded inside another dictionary, that is inside a list. Try something like this:
#...omitted code
for char_obj in dic["character_list"]:
if "character_id" in char_obj:
print(char_obj["character_id"])
if your dic is like {"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
you get the value of character_id by
print(dic['character_list'][0][character_id])
The problem here is that you're trying to access a dictionary where the key is actually character_list.
What you need to do is to access the character_list value and iterate over or filter the character_id you want.
Like this:
print(jsonString)
dic = json.loads(jsonString)
print(dic)
character_information = dic['character_list'][0] # we access the character list and assume it is the first value
print(character_information["character_id"]) # this is your character id
The way I see it, the only hiccup with the code is this :
if 'character_id' in dic:
print(dic['character_id'])
The problem is that, the JSON file actually consists of actually 2 dictionaries , first is the main one, which has two keys, character_list and returned. There is a second sub-dictionary inside the array, which is the value for the key character_list.
So, what your code should actually look like is something like this:
for i in dic["character_list"]:
print(i["character_id"])
On a side-note, it will help to look at JSON file in this way :
{
"character_list": [
{
"character_id": "5428662532301799649"
}
],
"returned": 1
}
,where, elements enclosed in curly-brackets'{}' imply they are in a dictionary, whereas elements enclosed in curly-brackets'[]' imply they are in a list

Iterating over A dict to access a specific key value

I have a list of dicts ('sortings') that I am trying to iterate through to access a values in one specific key of each dict. My code keeps saying that there is a key error for the desired value in the dict. If I print inside the for loop, it prints with the values entered but once I exit the for loop it says there is a key error.
for i in range(sort_len):
sentence = sortings[i]['content']
containing_messages.append(sentence)
print(containing_messages)
This is an answer for my understanding of the question. I would require the given input and expected output to provide a better answer.
list_of_dicts = [{'keya':'value1_1','keyb':'value2_1','keyc':'value3_1'},
{'keya':'value1_2','keyb':'value2_2','keyc':'value3_2'},
{'keya':'value1_3','keyb':'value2_3','keyc':'value3_3'}]
list_of_key_values = [my_dict['keyb'] for my_dict in list_of_dicts]
print list_of_key_values

Add multiple values to dictionary

Here is my code:
for response in responses["result"]:
ids = {}
key = response['_id'].encode('ascii')
print key
for value in response['docs']:
ids[key].append(value)
Traceback:
File "people.py", line 47, in <module>
ids[key].append(value)
KeyError: 'deanna'
I am trying to add multiple values to a key. Throws an error like above
Check out setdefault:
ids.setdefault(key, []).append(value)
It looks to see if key is in ids, and if not, sets that to be an empty list. Then it returns that list for you to inline call append on.
Docs:
http://docs.python.org/2/library/stdtypes.html#dict.setdefault
If I'm reading this correctly your intention is to map the _id of a response to its docs. In that case you can bring down everything you have above to a dict comprehension:
ids = {response['_id'].encode('ascii'): response['docs']
for response in responses['result']}
This also assumes you meant to have id = {} outside of the outermost loop, but I can't see any other reasonable interpretation.
If the above is not correct,
You can use collections.defaultdict
import collections # at top level
#then in your loop:
ids = collections.defaultdict(list) #instead of ids = {}
A dictionary whose default value will be created by calling the init argument, in this case calling list() will produce an empty list which can then be appended to.
To traverse the dictionary you can iterate over it's items()
for key, val in ids.items():
print(key, val)
The reason you're getting a KeyError is this: In the first iteration of your for loop, you look up the key in an empty dictionary. There is no such key, hence the KeyError.
The code you gave will work, if you first insert an empty list into the dictionary under to appropriate key. Then append the values to the list. Like so:
for response in responses["result"]:
ids = {}
key = response['_id'].encode('ascii')
print key
if key not in ids: ## <-- if we haven't seen key yet
ids[key] = [] ## <-- insert an empty list into the dictionary
for value in response['docs']:
ids[key].append(value)
The previous answers are correct. Both defaultdict and dictionary.setdefault are automatic ways of inserting the empty list.

Categories