Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. # <------------------------NORMAL FUNCTION -------------------------------->
  2.  
  3. # # Build and return a list
  4. # def getKeys(data):
  5. # return list(data.keys())
  6.  
  7. # obj = { 'bar': "hello", 'baz': "world" }
  8. # keys_list = getKeys(obj)
  9.  
  10. # <------------------------BEHIND THE SCENE ------------------------------->
  11. # # Using the generator pattern (an iterable)
  12. # class getKeys(obj):
  13. # print(obj.keys())
  14. # def __init__(self, obj):
  15. # self.obj = obj
  16.  
  17. # def __iter__(self):
  18. # return self
  19.  
  20. # # Python 3 compatibility
  21. # def __next__(self):
  22. # return self.next()
  23.  
  24. # def next(self):
  25. # if self.obj:
  26. # return list(obj.keys())
  27. # else:
  28. # raise ValueError('Dear Lord,Gimme object')
  29.  
  30.  
  31. # data = {'bar': "hello", 'baz': "world"}
  32. # keys_list = getKeys(data)
  33. # print(keys_list)
  34.  
  35. # <------------------------GENERATOR PATTERN ------------------------------->
  36.  
  37. # a generator that yields items instead of returning a list
  38.  
  39.  
  40. def getKeys(obj):
  41. if (type(obj) is dict):
  42. yield [obj.keys()]
  43. else:
  44. raise ValueError('Dear Lord,Gimme object')
  45.  
  46. data = {'bar': "hello", 'baz': "world"}
  47. keys_list = getKeys(data)
  48. print(list(keys_list))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement