So, odd issue. I'm creating a data structure to pull out some data from a Cudatel phone system for call reporting. 'aggregate' is a dictionary with keys matching dates, each of these keys contains a dictionary with the name of each of our call center people, and then under each of them is a dictionary of counts of each type of call and the total duration for the day. 'callrecord' is a list of calls with a timestamp, a name, a type, (inbound/outbound), and a duration in seconds.
The code I'm using is below, for some odd reason when the bolded parts are called the counts for every single user for every single date are getting updated. I know when you pass mutable object around in python it's something like pass by reference (ie they all get updated) however at least at the counts level I'm setting this up each time I need one. What's going on here?
aggregate = OrderedDict().fromkeys(
list(dates),
OrderedDict().fromkeys(
list(extensions.values())
)
)
for call in callrecord:
date = str(call['timestamp'])
name = call['name'].replace(' ', '_')
type = call['direction']
duration = call['duration']
try:
aggregate[date][name][type+'_calls']+=1
aggregate[date][name][type+'_duration']+=duration
except TypeError:
aggregate[date][name]=OrderedDict()
aggregate[date][name][type+'_calls']=1
aggregate[date][name][type+'_duration']=duration
答案 0 :(得分:0)
Answered my own question, nesting dicts with 'fromkeys' was the issue. Either the name or date or both dicts were being passed by reference. I threw out the prebuilt structure (which was a kludge to begin with) and did this (it's ugly but it works okay):
aggregate = OrderedDict()
count=0
for call in callrecord:
date = str(call['timestamp'])
name = call['name'].replace(' ', '_')
type = call['direction']
duration = call['duration']
try:
aggregate[date]
except KeyError:
aggregate[date]=OrderedDict()
try:
aggregate[date][name]
except KeyError:
aggregate[date][name]=OrderedDict()
try:
aggregate[date][name][type+'_calls']+=1
aggregate[date][name][type+'_duration']+=duration
except KeyError:
aggregate[date][name][type+'_calls']=1
aggregate[date][name][type+'_duration']=duration