I have the following code example where I am creating a dictionary result
for each id
with a tuple of 2 numbers for its value.
# populate the ids list (contents of the current directory which is for a speicif id name)
ids_list = [filename for filename in glob('*' + .txt)
def some_numerical_calc(filename):
# calculates and returns some number as string
def size_of_file(filename):
# calculates and returns size number as string
def count_stuff(id, filename):
result = { id: (some_numerical_calc(filename), size_of_file(filename)) }
for id in ids_list:
for f in files_list:
count_stuff(id, f)
The idea is that I will eventually aggregate all these dictionary key-value pairs under one dictionary (perhaps this parts needs redesigning..).
The problem I am dealing is for cases where the files_list
of a specific id
is greater than 1; in these cases I would like every 2 numbers inside the tuple for each filename
to be added with the previous numbers for that same filename
.
As an example,
ids_list = ['001', '002', '003']
where for
id='001'
it hasfiles_list=['file1.txt', 'file2.txt', 'file3.txt']
and if
some_numerical_calc('file1.txt')
gives10
andsize_of_file('file1.txt')
gives80
,
some_numerical_calc('file2.txt')
gives150
andsize_of_file('file2.txt')
gives35
,
some_numerical_calc('file3.txt')
gives30
andsize_of_file('file3.txt')
gives120
,then, I would expect the output for
id='001'
to beresult = { '001': (190, 235) }
I know that tuples are immutable. I am struggling to come up with an implementation to pre-compute the 2 numbers for all files for each id and then create its specific dictionary entry. Alternatively, perhaps I should remove the tuples structure -even though I was hoping to use namedtuples and store the 2 numbers in a set (?). Any suggestions are would be much appreciated.
Hoping for an efficient and pythonic suggestions.