pyhon:Solution of append “KeyError”,extend “TypeError: ‘NoneType’ object is not iterable”

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

I got an error when I work with the JSON format data from dictionary object(associative array) by using json module(import json) .

When you use "append" in pyhon to dictionary objects(associative array), you will be get "KeyError" if you access with a key that does not exist in the dictionary.
If it happens, you can fix using the "get()" function.

The below is sample code, data(data[]) and list (datalistA, datalistB).

data = {
	"menuitem": [
		{"value": ["New", "Open"]},
		{"value": ["Create", "Read"]},
		{"input": ["AAA", "BBB"]}
	]
}

datalistA = []
datalistB = []
for i in data['menuitem']:
		# datalistB.append(i['value']) # KeyError: 'value'
		datalistA.append(i.get('value')) # [['New', 'Open'], ['Create', 'Read'], None]

You should be use the "extend" rather than "append" when you unpleasant comes to nest list(multiple list).
But if you use the "get()" because of the key that does not exist in the dictionary, then will return "None".

"None" causes error "TypeError: 'NoneType' object is not iterable".
So, the solution is to use the "try-except-else statement".
Just write "pass" if you do not want to do anything at the part of the except-else.

# contents of the data are the same as examples of "append"
for i in data['menuitem']:
	try:
		datalistB.extend(i.get('value')) # ['New', 'Open', 'Create', 'Read']
	except TypeError:
		print "Someting" # If not "try-except-else" statement, "TypeError: 'NoneType' object is not iterable"
	else:
		pass
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.