Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Generate a dynamic dictionary from the list of keys

I do have a list as given below -

keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
value1 = "Roger"

How can I generate dynamic dictionary which can be retrieved as below -

mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"] = value

The list could be anything; Variable Length or consisting of "N" number of elements unknown to me...

Now I do have another list, so that My dictionary should be updated accordingly

keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
value2 = 25

i.e. If Keys "Person", "Male", "Boy", "Student", "id_123" already exists, the new key "age" should be appended ...

like image 509
Abhishek Kulkarni Avatar asked Jul 04 '13 04:07

Abhishek Kulkarni


1 Answers

I'm just learning python, so my code could be not very pythonic, but here's my code

d = {}

keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
value1 = "Roger"
value2 = 3

def insert(cur, list, value):
    if len(list) == 1:
        cur[list[0]] = value
        return
    if not cur.has_key(list[0]):
        cur[list[0]] = {}
    insert(cur[list[0]], list[1:], value)

insert(d, keyList1, value1)
insert(d, keyList2, value2)

{'Person': {'Male': {'Boy': {'Student': {'id_123': {'Age': 3, 'Name': 'Roger'}}}}}}
like image 57
Roman Pekar Avatar answered Sep 28 '22 16:09

Roman Pekar