Ch. 11 Weekly Assignment (lc101 - O'Fallon)

I see that back in August @ArtisticAng asked about sorting through the mess of dictionaries, lists and tuples in this assignment. I can sort the dictionary keys easily enough, but converting to a list of tuples eludes me. The recommendations for addressing that were quite opaque and I wonder if anyone can add more to the discussion.

Maybe this similar example can spark some thoughts:

humans = {"Tim": {"age": 22, "hair color": "brown", "favorite food": "pizza"},
          "Jane": {"age": 35, "hair color": "blonde", "favorite food": "stir-fry"},
          "Sam": {"age": 14, "hair color": "red", "favorite food": "chicken nuggets"}}
food_ages = []
for name in humans.keys():
    food_age = (humans[name]["favorite food"], humans[name]["age"])
    food_ages.append(food_age)
print(food_ages)

Results in:

[('pizza', 22), ('stir-fry', 35), ('chicken nuggets', 14)]

Remember that you can loop/iterate through the dictionary keys and values, and index them or refer to them as key and value. Can you use the key and value instances to populate a list of tuples? A list, you might recall, can take an “append” operation.

Hmmm, thanks, Ryan, but I’m not sure how to turn this into something actionable. You have nested dictionaries so you can address specific keys throughout, and each key has a single value associated with it. Mine doesn’t appear to be so straightforward.

I understand iterating through dictionary.keys() and using dictionary[key] to get a value, but the value here is a tuple. I’m not clear on how to extract the 2 elements from the tuple, combine them with the key, and then turn all that into a single tuple.

Once I have the resulting tuple I think it’s a straightforward process to list.append(tuple), but then I’m not clear on how to sort it. Maybe that’s done earlier in the process, but I don’t know where or how.

Clarity is proving elusive…

Okay, got it. Thanks for the help!