Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Dictionary adds an unexpected list
#1
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={}
Quote
#2
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 = {}, {}
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Exporting list with dictionary to Excel veromi22 0 117 Oct-15-2019, 12:54 AM
Last Post: veromi22
  Create a dictionary from a list klllmmm 3 155 Oct-06-2019, 05:50 PM
Last Post: Gribouillis
  pop default of two list of dictionary kk230689 1 106 Sep-10-2019, 12:12 PM
Last Post: ichabod801
  update values in list based on dictionary bunti 3 818 Jun-10-2019, 07:26 AM
Last Post: perfringo
  Search a List of Dictionaries by Key-Value Pair; Return Dictionary/ies Containing KV dn237 19 763 May-29-2019, 02:27 AM
Last Post: heiner55
  Iterate through a list of dictionary and append a new value. erina 1 263 May-16-2019, 09:55 AM
Last Post: perfringo
  Convert List of Dictionary to dictionary of dictionary list in python kk230689 2 432 Apr-27-2019, 03:13 AM
Last Post: perfringo
  Converting List of 3 Element Tuple to Dictionary fooikonomou 11 1,061 Jan-14-2019, 09:51 AM
Last Post: perfringo
  dictionary: print key/value with list(dict) comprehension wardancer84 4 521 Nov-14-2018, 03:14 PM
Last Post: wardancer84
  Get New List Based on Dictionary Key leoahum 4 774 Oct-03-2018, 02:09 PM
Last Post: leoahum

Forum Jump:


Users browsing this thread: 1 Guest(s)