Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Dictionary within dictionary?

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)

  • put those elements into a dictionary comprised of dictionaries
  • the 1st dictionary contains location and the 2nd dictionary which is made up of the type of the item and how much it costs

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.

like image 564
newtTongue Avatar asked Jul 16 '26 14:07

newtTongue


1 Answers

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
like image 133
Aasmund Eldhuset Avatar answered Jul 18 '26 13:07

Aasmund Eldhuset