[英]Dictionary: TypeError: 'bool'/'nonetype object' not iterable when looping in dictionary
For the following dictionary, 对于以下字典,
a1 = {'a2':{'name':'mic\xa0\xa0', 'age':'12\xa0\xa0', 'college':True, 'contact':''},
'a3':{'name':'sen\xa0\xa0', 'age':'23\xa0\xa0','college':True,'contact':''}}
When looping on dictionary and performing some action getting bool
object not iterable, if remove the boolean field( college
) from dictionary then error is coming for empty filed( nonetype
( contact
) object not iterable) 当在字典上循环并执行一些操作使
bool
对象不可迭代时,如果从字典中删除布尔字段( college
),则空字段将出现错误( nonetype
( contact
)对象不可迭代)
def t1():
a4 = {k :
{k2: ''.join([i if 32 < ord(i) < 126 else " " for i in v2])
for k2, v2 in v.items()} for k, v in a1.items()
}
return a4
a5 = t1()
print(a5)
Any help would be appreciated. 任何帮助,将不胜感激。
Just make a small change to check if v2
is a string using isinstance()
. 只需
isinstance()
更改即可使用isinstance()
检查v2
是否为字符串。 If it is a string, then iterate and do your operation. 如果是字符串,则进行迭代并执行操作。 Otherwise, return it unchanged.
否则,将其保持不变。
Example: 例:
def t1():
a4 = {
k : {
k2: ''.join([i if 32 < ord(i) < 126 else " " for i in v2])
if isinstance(v2, str) else v2 for k2, v2 in v.items()
}
for k, v in a1.items()
}
return a4
a5 = t1()
print(a5)
Output: 输出:
{
"a3": {
"age": "23 ",
"contact": "",
"college": True,
"name": "sen "
},
"a2": {
"age": "12 ",
"contact": "",
"college": True,
"name": "mic "
}
}
You may also want to add in a .strip()
to the result of the join()
in order to remove leading/trailing whitespace. 您可能还需要在添加
.strip()
到的结果join()
,以删除前导/尾随空白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.