Declaring a multi dimensional dictionary in python

后端 未结 8 1620
闹比i
闹比i 2020-12-08 02:03

I need to make a two dimensional dictionary in python. e.g. new_dic[1][2] = 5

When I make new_dic = {}, and try to insert values, I get a <

8条回答
  •  臣服心动
    2020-12-08 02:38

    For project, I needed to have 2D dict of class instances, where indeces are float numbers (coordinates). What I did, was to create 2D dict using default dict, and pass my class name as a type. For ex.:

    class myCoordinates:
        def __init__(self, args)
        self.x = args[0]
        self.y = args[1]
    

    and then when I tried to create dictionary:

    table = mult_dim_dict(2, myCoordinates, (30, 30))
    

    where function 'mult_dim_dict' defined as:

    def mult_dim_dict(dim, dict_type, params):
        if dim == 1:
            if params is not None:
                return defaultdict(lambda: dict_type(params))
            else: 
                return defaultdict(dict_type)
        else:
            return defaultdict(lambda: mult_dim_dict(dim - 1, dict_type, params))
    

    Note: you cannot pass multiple arguments, instead you can pass a tuple, containing all of your arguments. If your class, upon creation, does not need any variables to be passed, 3rd argument of function will be None:

    class myCoors:
    def __init__(self, tuple=(0, 0)):
        self.x, self.y = tuple
    
    def printCoors(self):
        print("x = %d, y = %d" %(self.x, self.y))
    
    
    def mult_dim_dict(dim, dict_type, params):
        if dim == 1:
            if params is not None:
                return defaultdict(lambda: dict_type(params))
            else:
                return defaultdict(dict_type)
        else:
            return defaultdict(lambda: mult_dim_dict(dim - 1, dict_type, params))
    
    dict = mult_dim_dict(2, myCoors, None)
    dict['3']['2'].x = 3
    dict['3']['2'].y = 2
    
    dict['3']['2'].printCoors()  # x = 3, y = 2 will be printed
    
    dict = mult_dim_dict(2, myCoors, (30, 20))
    dict['3']['2'].printCoors()  # x = 30, y = 20 will be printed
    

提交回复
热议问题