newtTongue
newtTongue

Reputation: 45

python: recursive dictionary of 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

gymnasium weights 15
market cereal 5    
gymnasium shoes 50   
saloon beer 3   
saloon whiskey 10   
market bread 5

which would result in this

{
  'gymnasium': {
     'weights': 15, 
     'shoes': 50
   }, 
   'saloon': {
      'beer': 3, 
      'whiskey': 10
   }
} 

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 cant figure out how to append the inner list to the outer list if an instance of the key in the outer list occurs.

I would like to do this recursively

 location_dict = {} #row #name day weight temp
 item_dict = {}
 for line in file:
    line = line.strip()
    location_dict[item_dict['location'] = item_dict`

Upvotes: 1

Views: 592

Answers (2)

Ricardo Alejos
Ricardo Alejos

Reputation: 452

Here is another solution.

yourFile = open("yourFile.txt", "r")
yourText = yourFile.read()
textLines = yourText.split("\n")
locationDict = {}
for line in textLines:
    k1, k2, v = line.split(" ")
    if k1 not in locationDict.keys():
        locationDict[k1] = {}
    else:
        if k2 not in locationDict[k1].keys():
            locationDict[k1][k2] = int(v)
        else:
            locationDict[k1][k2] += int(v)

print locationDict

Hope it helps!

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113988

this is a good use for setdefault (or defaultdict)

data = {}
for line in file:
    key1,key2,value = line.split()
    data.setdefault(key1,{})[key2] = value

print data

or based on your comment

from collections import defaultdict
data = defaultdict(lambda:defaultdict(int))

for line in file:
    key1,key2,value = line.split()
    data[key1][key2] += value

print data

Upvotes: 2

Related Questions