在 Python 中迭代字典并使用每个值

Fre*_*man 2 python dictionary

我正在尝试迭代一个如下所示的字典:

account_data = {"a": "44196397",
                "b": "2545086098",
                "c": "210623431",
                "d": "1374059147440820231",
                "e": "972970759416111104",
                "f": "1060627757812641792",
                "g": "1368361032796700674",
                "h": "910899153772916736",
                "i": "887748030304329728",
                "j": "1381341090",
                "k": "2735504155",
                "l": "150324112", }
Run Code Online (Sandbox Code Playgroud)

目标是使用每个 ID 来抓取一些数据,因此我得到了一个方法,该方法采用相应的 userID 并从中获取数据。起初,我对字典中的每个 ID 都有一个方法,但现在我想更改它,以便我得到一个迭代字典的方法,一次获取一个 ID 并发出 API 请求,如果完成,则发出下一个请求等等。

问题是我无法迭代字典,我总是只访问这里的第一个字典。

我对 Python 比较陌生,因为我主要使用 Java。也许字典对于这个任务来说是错误的数据结构?

任何帮助表示赞赏。

编辑:

这是我迭代字典的旧代码:

def iterate_over_dict():
    for key, value in account_data.items():
        return value
Run Code Online (Sandbox Code Playgroud)

然后我继续在此函数中使用 id:

def get_latest_data():

    chosen_id = iterate_over_dict()
    print('id: ', chosen_id)
    # get my tweets
    tweets = get_tweets_from_user_id(chosen_id)
    # get tweet_id of latest tweet
    tweet_id = tweets.id.values[0]
    # get tweet_text of latest tweet
    tweets = tweets.text.values[0]
    # check if new tweet - if true -> check if contains
    data = check_for_new_tweet(tweet_id, tweets)

    if data is not None:
        print("_________")
        print('1 ', data)
Run Code Online (Sandbox Code Playgroud)

但我总是只使用第一个。我认为在 Java 中这对我来说不是问题,因为我可以使用索引从 0 迭代到 n,但是字典有类似的东西吗?我还想在每次从字典中选择新 ID 时运行 get_latest_data 方法

fiv*_*nts 8

使用for循环进行迭代。

dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dict.items():
  print(key+" "+ str(value))

for key in dict:
  print(key+ " "+str(dict[key]))
Run Code Online (Sandbox Code Playgroud)

第一个迭代项目并为您提供键和值。第二个迭代键,然后使用键从字典中访问值。