Python Forum
Dictionary based exercise
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary based exercise
#1
Hi,

I am stuck with a problem and hoping someone can help.

How can I import data from a file and store them in a dictionary? I have a file named ‘bank.txt’. I need to import data and create a dictionary allowing the following features:


- Every line in the file will look like key: value pair.
- Key is a user's name and value is an amount to update the user's bank account with. The value should be a number, however, it is possible that there is no
value or that the value is an invalid number.
- If the key doesn't exist, create a new key: value pair.
- If the key does exist, increment its value with the amount.
- You should also handle cases when the value is invalid. If so, ignore that line and don't update the dictionary.

I am uploading the bank.txt file here as provided to me. Since I don’t know how to do this exercise, any sample code will be useful. Looking forward to your assistance.

Thanks and Regards,
Arvind Gupta
Reply
#2
What have you learnt about dictionaries and reading files? How have you thought about approaching this problem?
Reply
#3
Thanks for the response. I have just read the basic theory on dictionary and this is the first time I am trying to program using dictionaries. In particular, I don’t know the following:

** How to read from a file and store key value pair in dictionary.
** How to check a dictionary entry and update it if it isn’t updated.

My plan to approach the problem is simple.

1. Read the first set of key value pair.
2. Check if the value is a numeral. If yes, then store it as the first element of the dictionary.
3. Then, read the next pair of key value pair. Check if the value is a numeral.
4. If the key doesn’t exist, make a new key value pair entry. Otherwise update the value field.
5. Repeat steps 3 and 4 till there are no more entries in the given file.

Since this is the first time I am working on python and with dictionary feature, I am unable to execute the code. I hope you will be able to help me.

Thanks and Regards,
Arvind Gupta.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionary lookups exercise (PyBite #109) Drone4four 14 5,831 Aug-10-2020, 06:41 PM
Last Post: Intr0spective
  Dictionary based assignment: Need help RoyceJ 6 3,888 Aug-29-2018, 05:30 AM
Last Post: perfringo
  logic comparater based on dictionary values ijosefson 3 3,252 Oct-16-2017, 06:04 AM
Last Post: Mekire

Forum Jump:

User Panel Messages

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