Python Forum

Full Version: Dictionary based exercise
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
What have you learnt about dictionaries and reading files? How have you thought about approaching this problem?
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.