2
\$\begingroup\$

Currently learning from "LPTHW - Zed Shaw" and "Automating the boring stuff".

There is a nested dictionary of the type {'string1': {inner dict 1}, 'string2':{inner dict 2},...}.

I want a non nested consolidated dictionary of all the keys and values from all of the {inner dicts}. I have written the code below, but I am not convinced it is the most efficient way. I am looking for suggestions on how the code can be simplified by utilising logic within a single loop or by making use of some other modules and methods.

Is that new method efficient from a processing point of view?

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
           'Bob': {'ham sandwiches': 3, 'apples': 2},
           'Carol': {'cups': 3, 'apple pies': 1}}

item_list = []
count_list = []
consolidated = {}
all_items_list = list(allGuests.values()) #This is a list of sub dictionaries

#Loop for the number of guests who brought items
for guest in range(0, len(allGuests)):

#Creating 2 separate lists for 'items' and 'their count'

    item_list = item_list + list(all_items_list[guest].keys())
    count_list = count_list + list(all_items_list[guest].values())

#Creating a consolidated dictionary    
for index in range(0, len(item_list)):

    if not consolidated.get(item_list[index]):
        consolidated.setdefault(item_list[index], count_list[index])

    else:
        consolidated[item_list[index]] = consolidated[item_list[index]] + count_list[index]

    pprint.pprint(consolidated)

Expected output:

{'apple pies': 1, 'apples': 7, 'cups': 3, 'ham sandwiches': 3, 'pretzels': 12}
\$\endgroup\$
0
\$\begingroup\$

You can use .get method with default parameter.

consolidated = {}
for guest in allGuests.values():
    for key, value in guest.items():
        consolidated[key] = consolidated.get(key, 0) + value

Output: {'apples': 7, 'pretzels': 12, 'ham sandwiches': 3, 'cups': 3, 'apple pies': 1}

\$\endgroup\$
  • \$\begingroup\$ Could you also hint out why the OP's code isn't as efficient as yours? \$\endgroup\$ – dfhwze Jul 27 at 11:30
0
\$\begingroup\$

Below code worked as per one suggestion on stackoverflow

  consolidated = {}
  for guest in allGuests.values():
      for key, value in guest.items():
          if not consolidated.get(key):
              consolidated.setdefault(key, value)

          else:
              consolidated[key] = consolidated[key] + value

          pprint.pprint(consolidated)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.