Python Forum

Full Version: Dictionary adds an unexpected list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
my expected output is :
data={'Switchboard1':[{'Light':[1,2,3,4],'Fan':[1,2,3,4]}]}
But when the code executes the underlined point it adds the key "switchboard" to dic1,eventhough I initialize dic1 only with "delta".

    delta=[1,2,3,4]
    dic1=dic2={}
    data={'Switchboard1':['Light','Fan']}
    home= data.keys()
    for k, v in data.iteritems():
	    for i in v:
		    dic1[i]=delta
		    print dic1,k
		    [u]dic2[k]=dic1[/u]
		    print dic1
		    print dic2
		    dic1=dic2={}
Because of line 2, dic1 and dic2 are the same dict. Any changes you make to one are made to the other. Use this instead:

dic1, dic2 = {}, {}