473,422 Members | 2,059 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,422 software developers and data experts.

nested dictionary assignment goes too far

I'm attempting to build a process that helps me to evaluate the
performance of weather stations. The script below operates on an MS
Access database, brings back some data, and then loops through to pull
out statistics. One such stat is the frequency of reports from the
stations ('char_freq'). I have a collection of methods that operate on
the data to return the 'char_freq' and this works great. However, when
the process goes to insert the unique 'char_freq' into a nested
dictionary the value gets put into ALL of the sub-keys for all of the
weather stations. I have isolated (I think) the problem to the compound
key assignment in the next-to-last line before the print statements.
The result is that the last 'freq' to run throught the for loops gets
posted to all of the sensor_numbers. Eventually the process will put
in stats for the other keys in the nested dictionary, so that's why I
have set up the dictionary this way.

Thanks in advance!

run_flag=1
if run_flag > 0:

distinctID = runSQL(Unique_IDs)
distinctID = map(firstpart,distinctID) # converts the list of tuples
that is returned to a list of numbers
rain_raw_dict =
dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,'tip1':-6999,'tip2':-6999,'tip3':-6999,'tip4':-6999,'tip5':-6999,'tip6':-6999,'lost_rain':-6999})

rawList = runSQL(Rain_Raw_Count)

temp_list = [110,140,650,1440]

for sensor_count, sensor_number in enumerate(temp_list):
# get the frequency of timer reports for each rain gauge
# note that when a for loop is of the form "for X, x in
enumerate(xList)",
# X is an index value, and x is the value itself.
timerList = []
for icount, i in enumerate(rawList):
if i[0]==sensor_number:
for jcount in range(icount+1,len(rawList)): # look ahead to
the next values for comparison
if rawList[jcount][0]==sensor_number:
if rawList[icount][2]==rawList[jcount][2]:
temp = rawList[jcount][1]-rawList[icount][1]
timerList.append(temp)
icount = jcount-1
break

# now build a histogram of the time differences stored in
"timerList"
h = Histogram()
timer = h.histo(timerList)
sorted_timer = h.sorted_histo(timer)
freq = h.characteristic_freq(sorted_timer)
rain_raw_dict[sensor_number]['char_freq'] = sensor_number #
<<<< here's the problem!!
freq = -6999

print "ID = 110:",rain_raw_dict[110]
print "ID = 140:",rain_raw_dict[140]
print "ID = 650:",rain_raw_dict[650]
print "ID = 1440:",rain_raw_dict[1440]

Jun 26 '06 #1
3 2036
On 26 Jun 2006 16:56:22 -0700, Jake Emerson <ja**********@onerain.com> wrote:
I'm attempting to build a process that helps me to evaluate the
performance of weather stations. The script below operates on an MS
Access database, brings back some data, and then loops through to pull
out statistics. One such stat is the frequency of reports from the
stations ('char_freq'). I have a collection of methods that operate on
the data to return the 'char_freq' and this works great. However, when
the process goes to insert the unique 'char_freq' into a nested
dictionary the value gets put into ALL of the sub-keys for all of the
weather stations.
It's a sure sign you're sharing an object. In python, unless
specifically written, an assignment-like method doesn't create copies:
d = dict.fromkeys([1,2,3],[4,5,6])
id(d[1]) == id(d[2])

True

Instead of
rain_raw_dict =
dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,'tip1':-6999,'tip2':-6999,'tip3':-6999,'tip4':-6999,'tip5':-6999,'tip6':-6999,'lost_rain':-6999})


you should do something like this:

defaults = {'N':-6999,'char_freq':-6999,'tip1':-6999,'tip2':-6999,'tip3':-6999,'tip4':-6999,'tip5':-6999,'tip6':-6999,'lost_rain':-6999}
rain_raw_dict = {}
for ID in [110,140,650,1440]:
rain_raw_dict[ID] = defaults.copy()
Jun 27 '06 #2
Jake Emerson wrote:
However, when
the process goes to insert the unique 'char_freq' into a nested
dictionary the value gets put into ALL of the sub-keys


The way you're currently defining your dict:
rain_raw_dict =
dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,...})

Is shorthand for:
tmp = {'N':-6999,'char_freq':-6999,...}
rain_raw_dict = {}
for key in distinctID:
rain_raw_dict[key] = tmp

Note that tmp is a *reference*. Python does not magically create
copies for you; you have to be explicit. Unless you want a shared
value, dict.fromkeys should only be used with an immutable value (e.g.,
int or str).

What you'll need to do is either:
tmp = {'N':-6999,'char_freq':-6999,...}
rain_raw_dict = {}
for key in distinctID:
# explicitly make a (shallow) copy of tmp
rain_raw_dict[key] = dict(tmp)

Or more simply:
rain_raw_dict = {}
for key in distinctID:
rain_raw_dict[key] = {'N':-6999,'char_freq':-6999,...}

Or if you're a one-liner kinda guy,
rain_raw_dict = dict((key, {'N':-6999,'char_freq':-6999,...})
for key in distinctID)

--Ben

Jun 27 '06 #3
Thanks a lot Serge and Ben. Your posts were right on.

I hope the weather is good wherever you are.

Jake

Jun 27 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: omission9 | last post by:
I have a dictionary that looks like this MY_DICT=FOO I am having a problem updating this with a simple MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting into the inner...
9
by: T. Earle | last post by:
To list, I'm trying to figure out the best approach to the following problem: I have four variables: 1) headlines 2) times 3) states 4) zones
2
by: kbass | last post by:
I am new to Python and I am attempting to retrieve data from a database and I would like to place this data into a nested dictionary. After placing the data into a dictionary, I would like to loop...
5
by: Dave Benjamin | last post by:
I ran into an odd little edge case while experimenting with functions that create classes on the fly (don't ask me why): >>> def f(x): ... class C(object): ... x = x ... print C.x ......
6
by: B0nj | last post by:
I've got a class in which I want to implement a property that operates like an indexer, for the various colors associated with the class. For instance, I want to be able to do 'set' operations...
2
by: techiepundit | last post by:
I'm parsing some data of the form: OuterName1 InnerName1=5,InnerName2=7,InnerName3=34; OuterName2 InnerNameX=43,InnerNameY=67,InnerName3=21; OuterName3 .... and so on.... These are fake...
37
by: Tim N. van der Leeuw | last post by:
Hi, The following might be documented somewhere, but it hit me unexpectedly and I couldn't exactly find this in the manual either. Problem is, that I cannot use augmented assignment operators...
78
by: Josiah Manson | last post by:
I found that I was repeating the same couple of lines over and over in a function and decided to split those lines into a nested function after copying one too many minor changes all over. The only...
2
by: =?Utf-8?B?RGF2aWQgTW9ycmlz?= | last post by:
I am trying to create a nested Dictionary and get an error that seems odd to me. Here is my declaration: private IDictionary<Guid, IDictionary<Guid, string>> myNestedDictionary = new...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.