'NoneType' object has no attribute 'getitem_'和argument of type 'NoneType' is not iterable 错误的解决方法

'NoneType' object has no attribute '__getitem__'和argument of type 'NoneType' is not iterable 异常的解决办法

'NoneType' object has no attribute 'getitem_'和argument of type 'NoneType' is not iterable 错误的解决方法

python多线程采集新浪微博GPS数据,存入Mongodb。Mongodb要求经纬度的严格顺序为[longtitude, latitude],而微薄返回的顺序正好相反。所以在转换时,报出如上图所示异常:TypeError: 'NoneType' object has no attribute '__getitem__'。代码如下:

#extract one from queue
record = self.queue.get(True)
#import record into MongoDB
if record:
    record['geo']['coordinates'] = record['geo']['coordinates'][::-1]
    self.status.insert(record)
self.queue.task_done()

显然record可能不是dictionary,而为'None',所以在使用'[ ]'取值时就出现has no attribute '__getitem__'的异常。


之后将代码改为:

#extract one from queue
record = self.queue.get(True)
#import record into MongoDB
if record and ('geo' in record) and ('coordinates' in record['geo']):
    record['geo']['coordinates'] = record['geo']['coordinates'][::-1]
    self.status.insert(record)
self.queue.task_done()
以为搞定了,结果程序还是抛出了如下图异常:TypeError: argument of type 'NoneType' is not iterable。后来仔细一看发现,如果record and ('geo' in record)是一对,即使用'in'之前要保证record不是'None',那么('coordinates' in record['geo']似乎缺少保证record['geo']不为'None'。


于是将代码再改为如下,程序运行正常:

#extract one from queue
record = self.queue.get(True)
#import record into MongoDB
if record and ('geo' in record) and record['geo'] and ('coordinates' in record['geo']):
    record['geo']['coordinates'] = record['geo']['coordinates'][::-1]
    self.status.insert(record)
self.queue.task_done()

'NoneType' object has no attribute 'getitem_'和argument of type 'NoneType' is not iterable 错误的解决方法


为了证明分析原因的正确性,重现异常:

'NoneType' object has no attribute 'getitem_'和argument of type 'NoneType' is not iterable 错误的解决方法


所以在python集合中使用'in'和'[ ]'等操作符之前,要确保集合不为'None'类型。