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

Published on:
Last updated:

Sponsored Links

This post is also available in: Japanese

I am getting well when I work with the JSON format data from dictionary object (associative array) using json module(import json) .

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

This is sample data (data),and sample 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 will 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, Solution is to use the “try-except-else statement”. You 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

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


Sponsored Links