Python Forum
Dictionary adds an unexpected list
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={}
Reply
#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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionary in a list bashage 2 496 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 598 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Sort a list of dictionaries by the only dictionary key Calab 1 452 Oct-27-2023, 03:03 PM
Last Post: buran
  How to add list to dictionary? Kull_Khan 3 951 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  check if element is in a list in a dictionary value ambrozote 4 1,879 May-11-2022, 06:05 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 1,901 Apr-28-2022, 06:59 AM
Last Post: buran
  how to assign items from a list to a dictionary CompleteNewb 3 1,535 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 2,524 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,883 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  Python dictionary with values as list to CSV Sritej26 4 2,959 Mar-27-2021, 05:53 PM
Last Post: Sritej26

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020