[英]Iterate over a list of dictionary and string
I have a list of dictionaries converted from JSON but few keys seem to be Unicode which giving me trouble accessing the keys of the dictionary. 我有一个从JSON转换而来的词典列表,但似乎没有几个键是Unicode,这使我无法访问字典的键。 The list looks like this:
该列表如下所示:
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'}]
Now, I want to do something like this: 现在,我想做这样的事情:
l = [i["location"].get("street_1",None) for i in d]
But I'm getting the following error: 但我收到以下错误:
AttributeError: 'Unicode' object has no attribute 'get'
How can I work my way around that Unicode? 如何解决该Unicode问题? Thanks a lot for your help.
非常感谢你的帮助。
PS list d
contains more dictionaries than shown here and it contains more than just one Unicode. PS列表
d
包含的词典比此处显示的要多,并且不只包含一个Unicode。 When I iter over the dictionaries, I would like to have None
value for the location key with an empty Unicode value is encountered. 当我遍历字典时,我希望位置键的
None
值遇到空的Unicode值。
You could use this (rather unreadable) one-liner: 您可以使用此(不太可读)的单行代码:
>>> [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']
It's probably better to go with a full for-loop: 最好使用完整的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']
>>>
Essentially, use isinstance
to check if you are working with a dict
or not. 本质上,使用
isinstance
来检查您是否正在使用dict
。 If we are, use .get
, if we aren't, append the value. 如果是,则使用
.get
;否则,请附加值。 I use loc or None
which will evalute to None
if loc
is not truthy, which u""
happens to be not truthy. 我使用
loc or None
,如果loc
不为真,则将评估为None
,而u""
恰好不为真。
The alternative is a EAFP approach: 替代方法是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']
Whether or not it is more efficient to go with that or a LBYL approach depends on the nature of the data. 采用这种方法还是采用LBYL方法是否更有效取决于数据的性质。 If the "exception" is not truly exceptional, ie it occurs frequently, then a LBYL approach will actually be faster, even if EAFP is considered Pythonic.
如果“例外”并不是真正的例外,即它经常发生,那么即使将EAFP视为Pythonic,LBYL方法实际上也会更快。
Just modifying your attempt a little, using an empty dict as default. 只需稍微修改一下尝试,默认使用空字典即可。
>>> [(i['location'] or {}).get('street_1') for i in d]
[None, 'RR. E DURRESIT PALL. M.C.INERTE KATI 1 LAPRAKE']
As simple way would be: 一种简单的方法是:
for i in d:
location = i['location']
if location:
print(location.get('street_1', 'n/a')) # or whatever you want to do...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.