0

Suppose you have the following nested dictionary:

groceries = {
    'tom': {
        'apples': [1,0,1,0,1,0,1],
        'lettuce': [1,0,0,1,1,0,0]
    },
    'andy': {
        'oranges': [1,0,1,0,1,0,1],
        'eggplant': [1,0,0,1,1,0,0],
        'lettuce': [0,1,0,0,0,0,1]
     }
}

Tom and Andy are professional grocery shoppers and go shopping every day. Each list is a result of how many of each product they purchased a particular day of the week. I would like to generate an output list that provides a sum of products purchased for each day of the week for each shopper. The only way I can think to solve this is to iterate using a nested for loop such as:

for k,v in groceries.items():

    for i in v.items():

Is there a way to approach this that doesn't involve using a nested for-loop?

Paul P
  • 3,346
  • 2
  • 12
  • 26
paw4paw
  • 17
  • 2
  • Maybe you can use recursion. Not sure if that is the answer you are look for. – Yoshikage Kira May 23 '21 at 05:53
  • For recursion you can check [Loop through all nested dictionary values?](https://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values) – Yoshikage Kira May 23 '21 at 05:55
  • What keeps you from using double for-loop? It seems to be an appropriate usage. – Jun May 23 '21 at 06:19
  • 5
    However you would try to hide it, you have to iterate on the nested structure, so you will need nested loops. – Thierry Lathuille May 23 '21 at 06:35
  • 3
    Question is WHY would you not want a nested loop here? – Gulzar May 23 '21 at 08:17
  • This is why you shouldn't think of it as a nested dictionary, because it's not, in any way, a single object that can provide you with information about the lists. It's a dictionary, and its values happen to be *other* dictionaries that are unrelated to the first dictionary. – chepner May 23 '21 at 17:05
  • Express the data as nested XML and use xpath? – Paddy3118 May 24 '21 at 11:10
  • Express the data as indented text then use a regexp and Eval? This answer seems like code golf though. – Paddy3118 May 24 '21 at 11:12

0 Answers0