Python: Dictionary within dictionary?

Question:

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.

Asked By: newtTongue

||

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
Answered By: Aasmund Eldhuset

collections.defaultdict might be very useful to you, if you’re allowed to use stdlib. It automatically creates any keys that don’t already exist using a function you define, so:

import collections

dd = collections.defaultdict(dict)
dd['a']['b'] = "foo"

Will create a structure like:

{'a': {'b': 'foo'}}

If you can’t use defaultdict, you’ll have to either use dict.setdefault or test for membership before assigning to the deeper dict.

dd = {}
location, item, cost = ("gymnasium", "weights", 15)

# Either
if location in dd:
    dd[location][item] = cost
else:
    # dd[location] does not exist yet!
    dd[location] = {item: cost}

# Or
dd.setdefault(location, {})[item] = cost

# Or with defaultdict
ee = collections.defaultdict(dict)
ee[location][item] = cost  # creates automagically
Answered By: Adam Smith
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.