我有一个从JSON转换的字典列表,但是很少有键是Unicode的,这给我访问字典的键带来了麻烦。列表如下所示:
d = [{'location': u'',
'partner_id': '648746',
'partner_is_CSP': 'Y',
'partner_name': 'D4T4 SOLUTIONS PLC',
'partner_programs_tiers': [{'program_name': 'Cloud Service Provider',
'tier_name': 'Gold'}],
'partner_type': 'Direct Reseller; Service Provider',
'sort_value': '60',
'url_to_logo': u'',
'url_to_website': 'https://www.d4t4solutions.com/'},
{'location': {'address_type': 'H',
'city': 'Tirane',
'country': 'ALBANIA',
'geo_latitude': '41.348335',
'geo_longitude': '19.79865',
'phone': u'',
'point_of_contact': u'',
'state': u'',
'street_1': 'RR. E DURRESIT PALL. M.C.INERTE KATI 1 LAPRAKE',
'street_2': u'',
'street_3': u'',
'zip': '1023'},
'partner_id': '649341',
'partner_is_CSP': 'N',
'partner_name': 'COMMUNICATION PROGRESS',
'partner_programs_tiers': '[]',
'partner_type': 'Distribution VAR',
'sort_value': '0',
'url_to_logo': u'',
'url_to_website': 'www.commprog.com'}]
现在,我想这样做:
l = [i["location"].get("street_1",None) for i in d]
但我得到了以下错误:
AttributeError: 'Unicode' object has no attribute 'get'
我怎样才能解决这个问题?非常感谢你的帮助。你知道吗
p.S.listd
包含的字典比这里显示的多,而且它包含的Unicode不止一个。当我在字典上输入时,我希望遇到具有空Unicode值的location键的None
值。你知道吗
你可以用这个(相当不可读的)一行字:
最好使用完整的for循环:
本质上,使用
isinstance
检查您是否正在使用dict
。如果是,则使用.get
,如果不是,则附加值。我使用loc or None
,如果loc
不是真的,它将求值为None
,而u""
恰好不是真的。你知道吗另一种方法是EAFP方法:
使用这种方法或LBYL方法是否更有效取决于数据的性质。如果“异常”不是真正的异常,即它经常发生,那么LBYL方法实际上会更快,即使EAFP被认为是Pythonic。你知道吗
只是稍微修改一下你的尝试,使用一个空的dict作为默认值。你知道吗
简单的方法是:
相关问题 更多 >
编程相关推荐