首页 > 解决方案 > 将键值添加到字典中,而不会将键值对相互关联

问题描述

我创建了一个包含不同键和不同值的字典。当我更新一个键的值时,所有值都会更新并且相等。我不明白为什么会这样。我不明白为什么每个键的值都指向同一个内存位置,尤其是当它们是在不同时间创建时。

我试过使用更新方法。我试过通过做来分配值diction['new_value']= 'key_value'。我试过了from_keys()

def transform(self, rows):
    #Rows are a row from a csv, tsv, or txt file and I'm splitting them by white space, tabs, or commas. I've created an inherited function that does that for me called split_line.
    data = self.split_line(rows)
    for idx, column in enumerate(data):
        if idx != 0:
            if self.metadata_types[idx].lower() == 'numeric':
                column = round(float(column), 3)
            elif self.metadata_types[idx].lower() == 'group':
                if column not in self.uniqueValues:
                    self.uniqueValues.append(column)
        annotation =self.header[idx]
        self.annotation_subdocs[annotation]['value'].append(column)


def create_annotation_subdocs(self):
    annotation_subdocs = dict()
    #For ever value in the header I want to create a new dictionary with the key being the header value
    for idx, value in enumerate(self.header):
        if value == 'name':
            self.annotation_subdocs[value]= create_metadata_subdoc('text', idx, 'cells')
            print(id(annotation_subdocs[value]))
        elif value in ('x', 'y', 'z'):
            self.annotation_subdocs[value] = create_metadata_subdoc(value, idx, 'coordinates')
            print(id(annotation_subdocs[value]))
        else:
            self.annotation_subdocs[value]=create_metadata_subdoc(value, idx, 'annotations')
            print(id(annotation_subdocs[value]))

def create_metadata_subdoc(name, idx, header_value_type, *, value=[], subsampled_annotation=None):
return {
    'name': name,
    'array_index': idx,
    'value': value,
    'array_type': header_value_type,
    'subsampled_annotation': subsampled_annotation,
    'subsamp_threashold': "",
}

我希望每个键的值都不同。相反,即使我正在访问特定的键,所有值也会同时更新。

标签: python-3.xdictionary

解决方案


推荐阅读