'Looping through a nested list within a dictionary in python [duplicate]
In my loop_genre function i'm trying to loop through a nested list inside a dictionary. When i try to i'm unsuccessful. What i tried to do was words_list = dict['movies']['title']['genre'][1]['title']['genre'][2]['title']['genre'] which would allow me to iterate through the list without a loop but it defeats the purpose of the assignment which is to loop through nested values. The output should be a line containing commas after each word. Can anyone help me solve this? Thank you
Cheers
Liam
def main():
def name_id():
print("Hi Joe, my name is " + dict['name'] + ' ' 'and my student ID is ' + dict['student_id'] + '.')
def loop_pizzatoppings():
new_tuple = ('Tomatoes', 'Onions', 'Napalm')
for t in new_tuple:
dict['pizza_toppings'].append(t)
words_list = dict['pizza_toppings']
words_list.sort()
word = ''
for w in words_list:
word += w + "," " "
print("My ideal pizza has " + word)
def loop_genre():
word2 = ''
for w in dict['movies']['title']['genre']:
word2 += w + ', '
print("I like to watch " + word2)
def movie_loop():
word3 = ''
for w in dict['movies']:
word3 += w['title'] + ', '
print('Some of my favorites are ' + word3)
dict = {
'name': 'Liam',
'student_id': '10261507',
'pizza_toppings': [
'Pepperoni',
'Mushrooms',
'Peppers',
],
'movies': [
{'title': 'Star Wars',
'genre': [
'Sci-Fi',
'Action',
'Space opera',
'Adventure',
'Fantasy',
]
},
{'title': 'Deadpool',
'genre': [
'Comedy',
'Romance',
'Superhero',
]
}
]
}
extra_movie={'title': 'The Dark Knight Rises', 'genre': ['Drama', 'Thriller', 'Crime fiction']}
dict['movies'].append(extra_movie)
name_id()
loop_pizzatoppings()
loop_genre()
movie_loop()
main()
Solution 1:[1]
Update: Here are all the genres on one line (along with replacing the last comma with a period. As mentioned in the comments, this is not very pythonic. Hopefully someone else can give a better answer.
def loop_genre():
word2 = 'I like to watch '
for i in range(len(dict['movies'])):
for x in range(len(dict['movies'][i]['genre'])):
word2 += dict['movies'][i]['genre'][x] + ', '
print(word2[:-2] + '.')
Not sure if the output you are looking for is one genre per line, but here is a way to iterate through all of the genres. Basically it is just a nested for loop using index numbers instead of dict keys.
def loop_genre():
word2 = 'I like to watch '
for i in range(len(dict['movies'])):
for x in range(len(dict['movies'][i]['genre'])):
word2 = 'I like to watch ' + dict['movies'][i]['genre'][x]
print(word2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
