如何访问字典数组中的值?

2024-04-25 00:46:08 发布

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

我为数组中的两个帐户分别下载了10个follower,并将它们放入字典中,然后放入数组中。现在我需要访问第一个acc的4个followers屏幕名称和第二个acc的4个followers屏幕名称,但当我尝试这样做时,它会给我一个错误。下面是我使用的代码和下载的结果

twitter_accounts = ["AccName1", "AccName2"]
res = {}
pbar = tqdm_notebook(total=len(twitter_accounts))

for twitter_account in twitter_accounts:
    inner_structure = []
    for page in tweepy.Cursor(api.followers, screen_name=twitter_account,
                              skip_status=True, include_user_entities=False).items(10):
        val = page._json
        inner_dict = {}
        inner_dict["name"] = val["name"] 
        inner_dict["screen_name"] = val["screen_name"]
        if inner_dict not in inner_structure:
            inner_structure.append(inner_dict)

    res[twitter_account] = inner_structure
    pbar.update(1)

pbar.close()
print("done.")
for twitter_account in twitter_accounts:

    #print(len(res[twitter_account]))
    display(res[twitter_account]['screen_name'])

下面我将上传display(res[twitter_account])enter image description here结果的照片

我还上传了我试图访问display(res[twitter_account]['screen_name'])enter image description here时遇到的错误

我想访问我得到的追随者的屏幕名称,这样我就可以从他们中的4个下载他们的追随者。所以前两个账户的追随者


Tags: namein名称for屏幕restwitteraccount
2条回答

看起来你在试图访问数组

for twitter_account in twitter_accounts:
    inner_structure = res[twitter_account]  # access the array
    for inner_dict in inner_structure[:4]:  # go through the first 4 elements
        display(inner_dict['screen_name'])

如果您有>;=4个追随者:

for twitter_account in twitter_accounts:
    for in in range(4):
        display(res[twitter_account][i]['screen_name'])

相关问题 更多 >