提取{}中的某个位置

问题描述 投票:0回答:3

这是函数返回值的虚拟版本。我想知道如何提取

'[email protected]''Nextstringiwant来自:

{'blah': {'blah1': '[email protected]', 'blah2': 'Nextstringiwant'}, 'blah3': {'-note-': 'blah4', 'blah5': 'blah6', 'blah7': '[email protected]', 'blah8': 'blah9'}}

老实说,我不太清楚{}括号的用途或使用方法。我无法更改返回此函数。请帮助我,我迷路了。我的直觉告诉我,我应该将其转换为普通列表,然后在该列表中获得所需的位置,但它会返回此错误。

我的代码:

brackets = function().split(sep=':')
brackets.to_list()
email=brackets[2]
string=brackets[3]

错误:

brackets = creds.split(sep=':')
AttributeError: 'dict' object has no attribute 'split'

注意:这正是函数返回{}列表的方式,为简单起见,我仅更改了值。

我非常感谢

python
3个回答
0
投票
mydict = {
    'blah': {'blah1': '[email protected]', 
             'blah2': 'Nextstringiwant'}, 
    'blah3': {'-note-': 'blah4', 
              'blah5': 'blah6', 
              'blah7': 
              '[email protected]', 
              'blah8': 'blah9'}
}

[k_ for k_ in mydict.get("blah", dict()).values()]

输出:

['[email protected]', 'Nextstringiwant']

0
投票

如错误消息所指示,splitstring的属性/方法,而不是字典。

您的函数返回一个Python dictionary

鉴于您的函数称为function,您可以像这样访问值:

result = function()

email_address = result["blah"]["blah1"]  # this will be '[email protected]'

next_string = result["blah"]["blah2"]  # this will be 'Nextstringiwant'

您可以在此站点上获取有关Python词典的更多信息:https://realpython.com/python-dicts/


-1
投票

{}是Python中的json对象。如果该函数返回的是字符串,则应使用python的Json模块将其转换为json对象并访问其属性。例如:

import json
obj = json.loads(str_above)
print (obj.blah.blah1)
print (obj.blah.blah2)
© www.soinside.com 2019 - 2024. All rights reserved.