stackit
stackit

Reputation: 3106

Different Dictionaries sharing the same instance

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.

Upvotes: 1

Views: 58

Answers (1)

Óscar López
Óscar López

Reputation: 236004

Here's the problem:

[{}] * 7

Do this instead:

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

Explanation: the first line will create one dictionary and copy seven references to it in the list, whereas the second line creates seven different dictionaries - and that's what you want to do. Alternatively, as stated in the comments, this will also work:

[{} for _ in range(7)]

Upvotes: 5

Related Questions