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}