Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
nested dictionary
#1
Hi ,

I come from a perl background and used nested hash tables quite effectively and am unable to achieve the same using the python dictionary. Is it possible or not do something like this in python?

Reading a comma separated file into a deeply nested dictionary and printing it back out


inputfile = open('inputdata.csv','r')  # see bottom for the data file
count = 0
thisdict={}
#thisdict = {11:{12:{13:{14:{15:1}}}}}

for line in inputfile:
    line = line.rstrip("\n")
    items = line.split(",")
   
    if count != 0:
        thisdict[items[0]][items[1]][items[2]][items[3]][items[4]] = 1  ###this throws an error assignment is not acceptable
        pass
    count += 1

inputfile.close()


### the code below works if I am able to initialize the deeply nested dictionary using thisdict = {11:{12:{13:{14:{15:1}}}}}
    
print("number of lines read:", count)    
outfile = open('output2.txt','w')    
    
for col1 in thisdict:
    print(col1)
    for col2 in thisdict[col1]:
        print(col2)
        for col3 in thisdict[col1][col2]:
            print(col3)
            for col4 in thisdict[col1][col2][col3]:
                print(col4)
                for col5 in thisdict[col1][col2][col3][col4]: 
                    print(col5)
                    printline = str(col1) + "," +  str(col2) + "," + str(col3) + "," + str(col4) + "," + str(col5) + "," + str(thisdict[col1][col2][col3][col4][col5])  + "\n"
                    outfile.write(printline)
                
outfile.close()
#####inputdata.csv#####
Output:
col1,col2,col3,col4,col5 11,12,13,14,15 21,22,23,24,25 31,32,33,34,35 41,42,43,44,45 51,52,53,54,55 61,62,63,64,65 71,72,73,74,75 81,82,83,84,85
####end of inputdata.csv#######
Reply
#2
Please use proper tags while posting a thread - see BBCode to know more
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
the only problem I see is that you are not checking to see if enough values are provided in line, or if a value is not a valid key
if the list created by the split contains at least 5 items, this should work.
Proof:
>>> mydict = {
...     'A': {
...         'B': {
...             'C': {
...                 'D': {
...                     'E': 'hello there'
...                 }
...             }
...         }
...     }
... }
>>> line = "A B C D E"
>>> line = line.strip().split()
>>> line
['A', 'B', 'C', 'D', 'E']
>>> mydict[line[0]][line[1]][line[2]][line[3]][line[4]]
'hello there'
>>>
Reply
#4
There's a stackoverflow answer on creating a class that autovivifies dictionaries in a matter similar to perl.

https://stackoverflow.com/questions/6354...ctionaries
Reply
#5
thanks - not sure if I am reading your solution correctly but I want to read from the file and dynamically create a nested dictionary without explicitly using the assignment you show below:

mydict = {
...     'A': {
...         'B': {
...             'C': {
...                 'D': {
...                     'E': 'hello there'
...                 }
...             }
...         }
...     }
... }
Reply
#6
One can build such a dictionary from 'inside-out'. I have no idea in which data structures such dictionaries should be kept, so this code just prints them out:

with open('inputdata.csv') as f:
    header = next(f)
    for i, row in enumerate(f, start=1):
        nested_dict = i
        data = row.strip().split(',')
        for key in reversed(data):
              nested_dict = {int(key): nested_dict}
        print(nested_dict)
This will output:

Output:
{11: {12: {13: {14: {15: 1}}}}} {21: {22: {23: {24: {25: 2}}}}} {31: {32: {33: {34: {35: 3}}}}} {41: {42: {43: {44: {45: 4}}}}} {51: {52: {53: {54: {55: 5}}}}} {61: {62: {63: {64: {65: 6}}}}} {71: {72: {73: {74: {75: 7}}}}} {81: {82: {83: {84: {85: 8}}}}}
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
(May-28-2020, 04:15 PM)rkpython Wrote: thanks - not sure if I am reading your solution correctly but I want to read from the file and dynamically create a nested dictionary without explicitly using the assignment you show below:

That's what the autovivification class mentioned above does.

class Vividict(dict):
    """Per https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries"""
    def __missing__(self, key):
        value = self[key] = type(self)() # retain local pointer to value
        return value                     # faster to return than dict lookup

thisdict = Vividict()
thisdict['A']['B']['C']['D'] = "leaf data"
print(thisdict)
Output:
{'A': {'B': {'C': {'D': 'leaf data'}}}}
Reply
#8
Brilliant solution - exactly what I was looking for - thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 799 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Nested dictionary acting strange Pedroski55 2 2,054 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 4,426 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 2,560 Apr-18-2021, 07:54 AM
Last Post: michaelserra
  Nested Dictionary/List tonybrown3 5 3,074 May-08-2020, 01:27 AM
Last Post: tonybrown3
  Help: for loop with dictionary and nested lists mart79 1 1,840 Apr-12-2020, 02:52 PM
Last Post: TomToad
  Transforming nested key-tuples into their dictionary values ClassicalSoul 4 2,617 Apr-11-2020, 04:36 PM
Last Post: bowlofred
  How to change value in a nested dictionary? nzcan 2 5,723 Sep-23-2019, 04:09 PM
Last Post: nzcan
  Transform simplified dictionary to nested dictionaries bhojendra 1 2,324 Jul-02-2019, 02:05 PM
Last Post: ichabod801
  Nested dictionary issue Will86 3 2,912 Apr-16-2019, 11:58 PM
Last Post: Will86

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020