迭代字典和字符串列表

时间:2017-05-03 21:07:38

标签: python json list dictionary

我有一个从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'

我如何绕着Unicode工作?非常感谢你的帮助。

P.S。 list d包含的字典多于此处显示的字典,它不仅包含一个Unicode。当我浏览字典时,我希望位置键具有None值,并且遇到空的Unicode值。

3 个答案:

答案 0 :(得分:1)

你可以使用这个(相当难以理解的)单行:

>>> 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']
>>>

使用完整的for循环可能更好:

isinstance

基本上,使用dict检查您是否使用.get。如果是,请使用loc or None,如果我们不是,请附加值。我使用None,如果loc不真实,u""恰好不是真正的,则会>>> 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'] 评估。

替代方案是EAFP方法:

#include <stdlib.h>
#include <locale.h>
#include <stdio.h>
#include <wchar.h>

int main(void)
{

    /* Tell the C library to use the current locale settings. */
    setlocale(LC_ALL, "");

    /* Standard output is used with the wide I/O functions. */
    fwide(stdout, 1);

    /* Print some Greek text. */
    wprintf(L"Γειά σου Κόσμε!\n");

    return EXIT_SUCCESS;
}

使用该方法或LBYL方法是否更有效取决于数据的性质。如果&#34;例外&#34;不是真的例外,即经常发生,然后LBYL方法实际上会更快,即使EAFP被认为是Pythonic。

答案 1 :(得分:1)

只需稍微修改你的尝试,使用空字典作为默认值。

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

答案 2 :(得分:0)

简单的方法是:

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