遍历字典和字符串的列表

2024-09-26 18:12:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从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值。你知道吗


Tags: tonameidurlstreet列表partner字典
3条回答

你可以用这个(相当不可读的)一行字:

>>> [r['location'].get('street_1', None) if isinstance(r['location'], dict) else (r['location'] or None) for r in d]
[None, 'RR. E DURRESIT PALL. M.C.INERTE KATI 1 LAPRAKE']

最好使用完整的for循环:

>>> l = []
>>> for r in d:
...     loc = r['location']
...     if isinstance(loc, dict):
...         l.append(loc.get('street_1', None))
...     else:
...         l.append(loc or None)
...
>>> l
[None, 'RR. E DURRESIT PALL. M.C.INERTE KATI 1 LAPRAKE']
>>>

本质上,使用isinstance检查您是否正在使用dict。如果是,则使用.get,如果不是,则附加值。我使用loc or None,如果loc不是真的,它将求值为None,而u""恰好不是真的。你知道吗

另一种方法是EAFP方法:

>>> for r in d:
...     loc = r['location']
...     try:
...         l.append(loc.get('street_1', None))
...     except AttributeError:
...         l.append(loc or None)
...
>>> l
[None, 'RR. E DURRESIT PALL. M.C.INERTE KATI 1 LAPRAKE']

使用这种方法或LBYL方法是否更有效取决于数据的性质。如果“异常”不是真正的异常,即它经常发生,那么LBYL方法实际上会更快,即使EAFP被认为是Pythonic。你知道吗

只是稍微修改一下你的尝试,使用一个空的dict作为默认值。你知道吗

>>> [(i['location'] or {}).get('street_1') for i in d]
[None, 'RR. E DURRESIT PALL. M.C.INERTE KATI 1 LAPRAKE']

简单的方法是:

for i in d:
    location = i['location']
    if location:
        print(location.get('street_1', 'n/a'))  # or whatever you want to do...

相关问题 更多 >

    热门问题