[Python] Iterating over dictionary in Python and using each value

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to iterate over a dictionary that looks like this:

    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", }


    The goal is to use each ID to scrape some data, therefor I got a method that takes the corresponding userID and gets the data from it. At first I had a method for every ID in the dict, but now I want to change it so that I got one method which iterates over the dictionary, takes one ID at a time and makes the API request, if finished the next is made and so on.

    The problem is I can't iterate over the dictionary, I always just access the first one in here.

    I am relatively new to Python since I mainly used Java. Maybe dictionary is the wrong data structure for this task?

    Any help appreciated.

    Edit:

    This is my old code to iterate over the dictionary:

    def iterate_over_dict():
    for key, value in account_data.items():
    return value


    I then continue with using the id in this function:

    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)


    But I always only use the first one. I think in Java it wouldn't be a problem for me since I can just use an index to iterate from 0 to n, but is there something similar for dictionaries? I also want to run the get_latest_data method every time a new ID is chosen from the dict

    Continue reading...

Compartilhe esta Página