-4

I am new to python started few days back. Can anyone help me achieve following objective?

I have two lists -

mylist1 = ["Country", "State", "City", "Name", "Age"]

The another list -

mylist2 = [["India", "Maharashtra", "Mumbai", "Tom", 30],
           ["India", "Maharashtra", "Mumbai", "John", 40],
           ["India", "Maharashtra", "Pune", "Ronny", 25]
           ["India", "Madhya Pradesh", "Indore", "Jade", 35]]

The user will the level of dictionary e.g.

level = 4

So dictionary of depth 3 should be created as given below -

mydict = {"India":{"Maharashtra":{"Mumbai":{"Tom":{"Age":30},"John":{"Age":40}},
                                  "Pune"  :{"Ronny":{"Age":25}},
                   "Madhya Pradesh":{"Indore": {"Jade": {"Age" : 35}}}
               }

There could be some typos in above dictionary. I haven't tried anything to get this working.

Also note that, the above lists can be changed as follow -

mylist1 = ["State", "City", "Name", "Age"]

The another list -

mylist2 = [["Maharashtra", "Mumbai", "Tom", 30],
           ["Maharashtra", "Mumbai", "John", 40],
           ["Maharashtra", "Pune", "Ronny", 25]
           ["Madhya Pradesh", "Indore", "Jade", 35]]

Hence user may provide level = 3 in above case.

Ronu
  • 443
  • 1
  • 7
  • 16
  • 9
    AFAIK, people usually say `i have tried this to get this working:` but you're the opposite. Why don't you try anything first? You'll get better, too. – aIKid Feb 28 '14 at 07:49
  • I perhaps know how to make it, just haven't tried anything yet ;P – zhangxaochen Feb 28 '14 at 07:58
  • I'm afraid this isn't really a thorough enough explanation of the problem, and there's no code to speak of. – holdenweb Feb 28 '14 at 07:59

1 Answers1

0

This can be done using Autovivification. This answer provides the code to create nested dictionary using autovivification.

Adapting the code to your case, we can get to the output as:

from pprint import pprint
class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value


a = AutoVivification()
for entry in mylist2:
    a[entry[0]][entry[1]][entry[2]][entry[3]][mylist1[-1]] = entry[4]
pprint(a)

Further, you can change the indices for the entry based on the level parameter.

Hope this helps!

Community
  • 1
  • 1
shaktimaan
  • 10,886
  • 2
  • 25
  • 32