SHARE
TWEET

insert to dictionary using list of keys

furas Jul 28th, 2018 (edited) 91 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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) )
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top