Lorraine Lorraine - 4 days ago 7
Python Question

Referencing a value of a set within a list within a dictionary

Suppose I have a dictionary of lists, and each list element is a set.

Example:

from collections import defaultdict

shoppingList = defaultdict(list)

shoppingList["produce"].append( {"carrot",4} )
shoppingList["produce"].append( {"lettuce",2} )
shoppingList["produce"].append( {"tomato",2} )
shoppingList["dairy"].append( {"eggs",12} )


How would I reference the value of an individual set?

For example, if I want to print out specifically how many eggs I need (which is stored as the value "12" in {"eggs",12}) without knowing where in the list the set with key "eggs" is stored? Or if I want to edit the number of eggs?

Answer

Instead of using dictionary of lists containing sets you could just use nested dictionaries which would make access and update trivial:

from collections import defaultdict

shoppingList = defaultdict(dict)

shoppingList["produce"]["carrot"] = 4
shoppingList["produce"]["lettuce"] = 2
shoppingList["produce"]["tomato"] = 2
shoppingList["dairy"]["eggs"] = 12

print(shoppingList["dairy"]["eggs"]) # 12

shoppingList["dairy"]["eggs"] += 2
print(shoppingList["dairy"]["eggs"]) # 14
Comments