Search code examples
pythondictionarysyntaxnotation

Confused about python syntax


I have looked all over the web and have not been able to find an answer to my question. I am trying to understand some python code and came across a class declaration that looks like this:

s_list = []    
last_name = ""

def __init__(self, last_name, curr_date, difference):
    self.last_name = last_name
    self.s_list = {curr_date:difference}
    self.d_list = []
    self.d_list.append(curr_date)

What is happening inside the curly braces? Is this initializing a dictionary? Later in the main file it is used like this:

n = n_dict[last_name]
n.d_list.append(curr_date)
n.s_list[curr_date] = difference

Where n is a temporary dictionary used to add onto n_dict, with n_dict being a dictionary that contains information about the class.

Why is the {:} notation used? Is there any other way this could have been done?

Any answers much appreciated!


Solution

  • {curr_date:difference} created an anonymous dictionary.Instead, you can create a dictionary with a name :

    dict_name={}
    dict_name[curr_date]= difference
    self.s_list=dict_name
    

    Also, you can even create a dictionary using dict(): self.s_list=dict(curr_date=difference)

    There are some other ways to create a dictionary in python!