How to transform into a dictionary the value of a string in a list?

courses = [“French”, “Mathematics”, “Sport”]
I would like that at each loop turn, that it can create:

French = {
  "group" : [1,2,3]
  "note" : 0.0
}
Mathematics = {
  "group" : [1,2,3]
  "note" : 0.0
}
Sport = {
  "group" : [1,2,3]
  "note" : 0.0
}
2 Likes

Hi @fullbringcoder,

Are you trying to create three variables, dynamically, that refer to the dictionaries? If so, you can do this:

courses = ["French", "Mathematics", "Sport"]

for course in courses:
    globals()[course] = {
        "group" : [1,2,3],
        "note" : 0.0
    }

Now you have three variables named French, Mathematics, and Sport. You’ll need an organized system for keeping track of those variables.

Edited on March 19, 2019 to add the following:

Later on in the program, you can do something like this:

course_name = input("\nGrade Lookup: Which course? ")
if course_name in courses:
    print("Grade: {:0.1f}".format(globals()[course_name]["note"]))
else:
    print("No such course {:s}".format(course_name))

However, programs that manage variables in such a dynamic manner can easily become buggy and cumbersome to develop.

Is there a good reason why you want to do it this way?

3 Likes

Thank you for your reply. I like your first code because it works. But I have a concern about your second code which is :

course_name = input("\nGrade Lookup: Which course? ")
if course_name in courses:
    print("Grade: {:0.1f}".format(globals()[course_name]["note"]))
else:
    print("No such course {:s}".format(course_name))

I don’t understand
print("Grade: {:0.1f}".format(globals()[course_name]["note"]))
Please can you explain it well ? When I tried to execute it, I put French but it returns
KeyError: French

The first code and the second code need to be placed in the same program. The following was executed in Python 3.7.0 using IDLE:

courses = ["French", "Mathematics", "Sport"]

for course in courses:
    globals()[course] = {
        "group" : [1,2,3],
        "note" : 0.0
    }

course_name = input("\nGrade Lookup: Which course? ")
if course_name in courses:
    print("Grade: {:0.1f}".format(globals()[course_name]["note"]))
else:
    print("No such course {:s}".format(course_name))

Interactive console:

Grade Lookup: Which course? French
Grade: 0.0

This statement displays formatted output:

print("Grade: {:0.1f}".format(globals()[course_name]["note"]))

Within it, the globals() built in function accesses Python’s dictionary of global names. The three variables, French , Mathematics , and Sport, are included in that dictionary.

Also within the above statement, this expression uses the user’s input, for example "French", to access the dictionary referenced by the global variable of that name:

globals()[course_name]["note"]

From that dictionary, the value associated with the "note" key is output.

As stated in my previous post, programs that manage variables in such a dynamic manner can get cumbersome to maintain. Consider, instead, creating a dictionary with the course names as keys. The values would represent the information associated with each course. Those values could be either dictionaries or instances of a Course class that you create.

Edited on March 21, 2019 to add the following:

As we know, the names of Python variables cannot include spaces. However, the names of courses are often composed of more than one word. Refining the code above, let’s add a “World History” course:

courses = ["French", "Mathematics", "Sport", "World History"]

Now, we’ll run the program. Output:

Grade Lookup: Which course? World History
Grade: 0.0

Whoa, it worked! However the global namespace dictionary now includes an invalid variable name, World History. We got away with it for now, but can we be confident that this will not haunt us later on as we continue to develop the program?

Python dictionaries are a wonderful device, so much so, in fact, that they play a major role in the Python interpreter. For example, they are used to keep track of the global namespace. Why not use our own dictionary to keep track of the course names and the associated information? While the names of variables cannot include spaces, dictionary keys can include them, therefore among other benefits, this allows us flexibility in naming the courses.

You’re right. Because when I used globals()[course_name]["note"], I couldn’t use precisely the dictionary which was "French" since I wanted to access to the key "note" in order to change the list of the notes

I changed the structure of my code but it have a problem:

courses = ["French", "Mathematics", "Sport"]
students = ['Sarah','Peter']
group_name = ""
note = 0.0
matters = {}

def create_group(d, name_course, name_group, names, note_group):
    d[name_course] = {
        name_group : {
            "members_names" : names,
            "note" : note_group
        }
    }
    print(d)

course = courses[1]

for new_item in range(5):
    group_name = "Group" + str((new_item+1))
    create_group(matters, course, group_name, students, note)

I would like the following result:

matters = {
    "Mathematics" : {
        Group1 : {"members_names": ['Sarah','Peter'], "note": 0.0},
        Group2 : {"members_names": ['Sarah','Peter'], "note": 0.0},
        Group3 : {"members_names": ['Sarah','Peter'], "note": 0.0},
        Group4 : {"members_names": ['Sarah','Peter'], "note": 0.0},
        Group5 : {"members_names": ['Sarah','Peter'], "note": 0.0}
}

But it displays the following result:

matters = {
    "Mathematics" : {
        Group5 : {"members_names": ['Sarah','Peter'], "note": 0.0}
}

Why it doesn’t append to each time, to the dictionary ?

Hi @fullbringcoder,

The desired result that you decribe for matters is a dictionary that contains a key, "Mathematics", with the value associated with that key being a dictionary with five keys, with each of those keys referring to one of the groups.

Your current version of the create_group function overwrites whatever is already associated with the key for a course, such as "Mathematics", so you wind up with only one group.

First, add a key, "Mathematics", to matters that maps to an empty dictionary:

matters["Mathematics"] = {}

Use the following revised create_group function to add each group to that dictionary:

def create_group(d, name_course, name_group, names, note_group):
    d[name_course][name_group] = {
            "members_names" : names,
            "note" : note_group
    }
    # print(d)

Execute your for loop to populate the dictionary.

1 Like

Thanks a million. I didn’t know that method.

Please sorry to have answered quickly :confused:. I hadn’t tested the code yet. In fact, the code you proposed

def create_group(d, name_course, name_group, names, note_group):
    d[name_course][name_group] = {
            "members_names" : names,
            "note" : note_group
    }

It doesn’t work. It returns a Key error

Since I had forgotten to write matters["Mathematics"] = {}, I have written it. But it put
NameError: name 'matters' is not defined

Here’s the code:

courses = ["French", "Mathematics", "Sport"]
students = ['Sarah','Peter']
group_name = ""
note = 0.0
matters = {}

matters["Mathematics"] = {}
def create_group(d, name_course, name_group, names, note_group):
    d[name_course][name_group] = {
            "members_names" : names,
            "note" : note_group
    }

course = courses[1]

for new_item in range(5):
    group_name = "Group" + str((new_item+1))
    create_group(matters, course, group_name, students, note)

for key in matters["Mathematics"]:
    print(key, matters["Mathematics"][key])

Output:

Group1 {'members_names': ['Sarah', 'Peter'], 'note': 0.0}
Group2 {'members_names': ['Sarah', 'Peter'], 'note': 0.0}
Group3 {'members_names': ['Sarah', 'Peter'], 'note': 0.0}
Group4 {'members_names': ['Sarah', 'Peter'], 'note': 0.0}
Group5 {'members_names': ['Sarah', 'Peter'], 'note': 0.0}
1 Like