mylearning
mylearning

Reputation: 65

Create nested dictionary with same keys from a file

For example with the txt file of:

Math,Calculus,5
Math,Vector,5
Language,English,4 
Language,Spanish,4

into a dictionary of:

{
  "Math": {
    "Calculus": "5",
    "Vector": "5"
  },
  "Language": {
    "English": "4",
    "Spanish": "4"
  }
}

I have been able to write the structure, but cannot solve duplicate keys:

file = open(filename, mode='r')
dict={}
for line in file:
    line=line.rstrip()
    department, name, cre = line.split(';')
    if department not in dict:
        data = {}
        dict[department] = data
        data[name]=cre
    else:
        ????

Upvotes: 0

Views: 607

Answers (3)

claudio-bon
claudio-bon

Reputation: 1

Some notes about your code.
The split seems to be done wrongly (you should have used "," instead of ";")
Try to not name variables as type names (dict is the type name of the dictionary).
Close the file at the end.

This is the solution:

file = open(filename, mode='r')
d={}
for line in file:
    line=line.rstrip()
    department, name, cre = line.split(',')
    if department not in d:
        d[department] = {}
    d[department][name] = cre
file.close()

Upvotes: 0

larsks
larsks

Reputation: 312158

You could do something like this:

import json

with open('data.csv', mode='r') as fd:
    data={}
    for line in fd:
        line = line.rstrip()
        department, name, cre = line.split(',')
        if department not in data:
            data[department] = {name: cre}
        else:
            data[department][name] = cre

print(json.dumps(data, indent=2))

I've made a few changes to your code with an eye towards best practices:

  • Using with ... instead of just opening the file (this ensures the file gets closed)
  • Replace variable names that conflict with Python built-in types (like file and dict)
  • Fixing your split expression to use , (the actual separator) rather than ;

I'm using the json module here just to print out the result; obviously you don't need that.

Running the above produces:

{
  "Math": {
    "Calculus": "5",
    "Vector": "5"
  },
  "Language": {
    "English": "4",
    "Spanish": "4"
  }
}

Upvotes: 0

dukkee
dukkee

Reputation: 1122

d = {}

for line in file:
    line = line.rstrip()
    department, name, cre = line.split(',')

    if department not in d:
        d[department] = {}

    d[department][name] = cre

Upvotes: 1

Related Questions