1

I have some 7 dictionaries in a program whose data is fetched using ETREE , the problem is that python does not create a separate dict instance for each dict as shown in the output , whenever I print any of these dicts I get the same output which is a large dictionary having a union of all data.

 tr_dict,tr_text,exp_dict,exp_text,top_dict,top_text,times=[{}]*7 #create n empty dictionaries
    for tr in transcript:
        trtext = tr.find('TATION/ANNOTATION_VALUE').text
        tr_time_ref = tr.find('TATION').attrib['TIME_SLOT_REF1']
        tr_ann_ref = tr.find('ATION').attrib['ANNOTATION_ID']

        tr_dict[tr_ann_ref] =  tr_time_ref
        tr_text[tr_time_ref]=trtext

...

Output:

[Dbg]>>> exp_dict is exp_text
True
[Dbg]>>> tr_dict is tr_text
True
[Dbg]>>> tr_dict is exp_dict
True

Ofcourse I dont want this to happen , I want python to create and use a seperate dict for each.

4

1 回答 1

5

这是问题所在:

[{}] * 7

改为这样做:

[{}, {}, {}, {}, {}, {}, {}]

说明:第一行将创建一个字典并在列表中复制七个对它的引用,而第二行创建七个不同的字典 - 这就是您想要做的。或者,如评论中所述,这也将起作用:

[{} for _ in range(7)]
于 2013-08-21T19:25:53.430 回答