Defining Multiple Dictionaries Within a Loop in Python

dictionary, loops, python

Solution

I think instead of creating a variable for each name you can create a dict of names with each name pointing to a dictionary.

>>> names=["lloyd", "alice", "tyler"]
>>> keys=["homework", "quizzes", "tests"]
>>> dic={ name.capitalize():{ key:[] for key in keys} for name in names}
>>> dic
{'Tyler': {'quizzes': [], 'tests': [], 'homework': []}, 
 'Lloyd': {'quizzes': [], 'tests': [], 'homework': []},
 'Alice': {'quizzes': [], 'tests': [], 'homework': []}}

Now to access `Tyler` simply use:

>>> dic['Tyler']
{'quizzes': [], 'tests': [], 'homework': []}

Problem

What I'm looking to do is to define three very similar dictionaries with only subtle differences. If you recognize this it is one of the problems from the Codeacademy course on Python, and I'm looking to do it a little more elegantly. Anyways, here's what I have: ``` import string for name in ["lloyd", "alice", "tyler"]: name = {"name": string.capitalize(name), "homework": [], "quizzes": [], "tests": []} ``` This isn't working. What I want is three dictionaries, which have the names "lloyd" "alice" and "tyler" and with keys of their names (but capitalized), "homework", "quizzes", and "tests" To clarify, the output I want is equivalent to this: ``` lloyd = {"name": "Lloyd", "homework": [], "quizzes": [], "tests": []} alice = {"name": "Alice", "homework": [], "quizzes": [], "tests": []} tyler = {"name": "Tyler", "homework": [], "quizzes": [], "tests": []} ```

Original source