0

I need to create three dictionaries. I want to use a for loop to do this, but it is not turning out the way I want it to. This is my code:

names=["lloyd", "alice", "tyler"]

for name in names:
    name = {
        "name": [name],
        "homework": [],
        "quizzes": [], 
        "tests":[],
        }

The three dictionaries are being created, but are stored in the variable name. I assumed the second name (after the line starting the for loop) would also be substituted with the values stored in names, but this does not happen. How come? How can I fix this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Vincent
  • 240
  • 2
  • 10
  • 3
    `name` is a separate reference one of the strings in the list; setting it to reference another object (like the dictionary) won't change what the list references. – Martijn Pieters Jul 04 '15 at 21:15
  • 3
    Why on earth would you assume that? Strings are **not** the same as identifiers, although Python offers various options for converting between them if you do so explicitly. Doing so implicitly would be incredibly frustrating. – jonrsharpe Jul 04 '15 at 21:15
  • @jonrsharpe, did you actually try and read the first two words of my post? Also, would you mind to go into a little more detail and help me out? I would very much appreciate that. – Vincent Jul 04 '15 at 21:17
  • 1
    So? As a self-confessed *"noob"* you should be even more careful about making assumptions rather than doing research. Why not try following a structured tutorial? This is probably worth a read, too: http://nedbatchelder.com/text/names.html – jonrsharpe Jul 04 '15 at 21:19

1 Answers1

1
names=["lloyd", "alice", "tyler"]

name_dicts = []

for name in names:
    name_dicts.append({
        "name": [name],
        "homework": [],
        "quizzes": [], 
        "tests":[],
        })

Now you have an array of dictionaries with all the names.

Try to avoid using the same variable name for different things as per @johnsharpe (you should read his link - very helpful)

Sina Khelil
  • 2,001
  • 1
  • 18
  • 27