So I have a piece of code below which consists of two dictionaries whose keys ar
ID: 3664046 • Letter: S
Question
So I have a piece of code below which consists of two dictionaries whose keys are phone numbers(the 3rd column of the call text file). I've copied only part of the call text file but it is much longer(thousands of lines). The phone numbers are repeated in the file. When I'm trying to create the dictionary, it stops reading and printing once it encounters a key(phone number) which is already in the dictionary. And I need the whole list in one dictionary, I'm guessing I can't choose phone number as a key because of repetition but I don't know how else to do it.
# Open the file
call_file = open('calls.txt','r')
# Initially empty lists
callerList = []
durList = []
rateList = []
due={}
cent={}
for lines in call_file:
callFile = lines.rstrip(' ')
callFile = callFile.split(';')
timeStamp = callFile[0]
caller = callFile[1]
receiver = callFile[2]
duration = callFile[3]
rate = callFile[4]
callFile.remove(timeStamp)
callFile.remove(receiver)
caller1=callFile[0]
duration1=callFile[1]
duration1=int(duration1)
rate1= callFile[2]
rate1 = float(rate1)
due[caller1] = duration1
cent[caller1] = rate1
1419121443;7803214567;7808907654;94;0.22
1419122088;7804922860;7801236789;602;0.23
1419123851;7801234567;7809876543;910;0.21
1419123958;7808765432;7801236789;925;0.22
1419123983;7804922860;7804321098;631;0.10
1419125014;7809876543;7808765432;275;0.24
1419126352;7809876543;7804321098;185;0.10
1419127903;7808907654;7808765432;338;0.12
1419129259;7807890123;7808765432;599;0.26
1419130776;7801234567;7804321098;177;0.30
1419132478;7804321098;7801236789;79;0.36
1419132898;7801236789;7804321098;252;0.17
1419133049;7803214567;7807890123;200;0.30
1419134654;7808907654;7807890123;881;0.22
1419136224;7808765432;7804321098;512;0.18
1419137462;7803214567;7808765432;761;0.17
1419138857;7801236789;7804321098;597;0.28
1419139989;7804321098;7804922860;64;0.40
1419140723;7808907654;7801236789;890;0.22
1419142590;7809876543;7804321098;232;0.23
1419143715;7804922860;7808907654;373;0.13
Explanation / Answer
You should use TimeStamp as a key, because timestamp will be different for each record.
Let me know in case you have any problem.
For reference, key operation:
HashMap<String, Float> dic = new HashMap<String, Float>();
while(your_condition){
String phone_number= "xyz"; // let's assume new phone number is xyz
if(dic.containsKey(phone_number)) { // checking if this phone number already exist or not
float cost = dic.get(phone_number);// getting existing cost for this mobile number
float total_cost = cost + cost_for_phone_number_XYZ; // adding new cost to old to get total for this mobile number
dic.put("xyz", total_cost); // replacing old cost with new one
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.