Advertisement
furas

insert to dictionary using list of keys

Jul 28th, 2018
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. def insert(dictionary, tree, value):
  2.     '''it will create key if doesn't exist'''
  3.  
  4.     for key in tree[:-1]: # without last key
  5.         if key not in dictionary:
  6.             dictionary[key] = {}
  7.         dictionary = dictionary[key]
  8.  
  9.     dictionary[tree[-1]] = value # last key
  10.  
  11. def get(dictionary, tree):
  12.     '''it will raise error if key doesn't exist'''
  13.    
  14.     for key in tree: # without last key
  15.         dictionary = dictionary[key]
  16.  
  17.     return dictionary # last key
  18.  
  19. #------------------------------------------------------
  20.  
  21. usr = {}
  22.  
  23. comment = 'hello world'
  24. tree = ['acc', 'timeline', 'last_post', 'comments']
  25.  
  26. insert(usr, tree, comment)
  27. print(usr)
  28.  
  29. print( get(usr, tree) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement