I need help with a pretty simple exercise I am trying to execute, just syntactically I'm a bit lost.
Basically I read in a very brief text file containing 15 lines of 3 elements (essentially 2 keys and a value)
For Example:
Location Item Cost ------------------------ gymnasium weights 15 market cereal 5 gymnasium shoes 50 saloon beer 3 saloon whiskey 10 market bread 5
Which would result in
{'gymnasium': {'weights': 15, 'shoes': 50} and so on for the other keys
Basically I need to loop through this file but I'm struggling to read in the contents as a dict of dicts. Moreover without that portion i can't figure out how to append the inner list to the outer list if an instance of the key in the outer list occurs.
This looks like homework, so I'll only provide a few hints.
You probably know that this is how you create a new dictionary:
d = {}
Adding an entry to a dictionary:
d[key] = value
More specifically, adding an entry whose key is a string and whose value is another dictionary:
d["gymnasium"] = {}
Now, whenever you write d["gymnasium"] as a part of a larger expression, you'll get access to that inner dictionary, and you can perform the usual dictionary operations on it, e.g. using [] and = to add something to it:
d["gymnasium"]["weights"] = 15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With