Home > Software design >  Iterating over dictionary in Python and using each value
Iterating over dictionary in Python and using each value

Time:09-17

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

CodePudding user response:

You can do this by turning the dictionary into a list comprised of only the values.

val = list(account_data.values())

Would give you ["44196397", "2545086098", "210623431"...]

Which you can then very easily iterate over in a for loop without needing to worry about the key at all.

CodePudding user response:

Use for loop for iteration.

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]))

The first one iterates over items and gives you keys and values. The second one iterates over keys and then it is accessing value from the dictionary using the key.

  • Related