Reputation: 295
If I have the following nested dict:
dicta = {'Saturday, August 26': {"Hawai'i": 'Massachusetts', 'Portland State': 'BYU', 'Oregon State': 'Colorado State', 'South Florida': 'San José State', 'Stanford': 'Rice'}}
If I wanted to access the games (which are themselves values of the outer key), is the only way to get to them is with a throwaway variable like:
for day in dicta:
game_day = day
for home, away in day_dict[game_day].items():
print(home, away)
I don't really care about the variable game_day
as I already know the dict in question has the games in it I need. But I do need to access those games. So do I have to go about creating a variable just to get key:value pairs I need? Just trying to figure out a better way if there is one.
Edit: Update dict variable to same name as name in for loop
Upvotes: 2
Views: 280
Reputation: 3832
Since your sample dictionary has a different name than the ones you used in the loop, it is not very clear to me what you're trying to do, but seems like you are looking for a more efficient way to traverse your dictionary and finding the values you want.
For that matter I recommend checking out the Python documentation on dictionaries, it is pretty helpful and introduces a lot of useful functions.
So one thing that might help you is the keys() and values() attributes of an= dictionary object. You can get a list of all the dictionary's keys by making a loop like:
for key in dict.keys():
# do things with key
Or you can do things with the values of your dictionary like this:
for value in dict.values():
# do things with value
Hope that's helpful!
Upvotes: 1
Reputation: 71451
If you wish to access just the games without specifying the day, you can try this:
for a, b in dicta.items():
for c, d in b.items():
print "opponent 1: ", c
print "opponent 2: ", d
Upvotes: 0
Reputation: 3157
If you know the day before you iterate over the items in the dictionary, why not just do:
day = 'Saturday, August 26'
for home, away in day_dict[day].items():
print home, away
Upvotes: 1