Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # <------------------------NORMAL FUNCTION -------------------------------->
- # # Build and return a list
- # def getKeys(data):
- # return list(data.keys())
- # obj = { 'bar': "hello", 'baz': "world" }
- # keys_list = getKeys(obj)
- # <------------------------BEHIND THE SCENE ------------------------------->
- # # Using the generator pattern (an iterable)
- # class getKeys(obj):
- # print(obj.keys())
- # def __init__(self, obj):
- # self.obj = obj
- # def __iter__(self):
- # return self
- # # Python 3 compatibility
- # def __next__(self):
- # return self.next()
- # def next(self):
- # if self.obj:
- # return list(obj.keys())
- # else:
- # raise ValueError('Dear Lord,Gimme object')
- # data = {'bar': "hello", 'baz': "world"}
- # keys_list = getKeys(data)
- # print(keys_list)
- # <------------------------GENERATOR PATTERN ------------------------------->
- # a generator that yields items instead of returning a list
- def getKeys(obj):
- if (type(obj) is dict):
- yield [obj.keys()]
- else:
- raise ValueError('Dear Lord,Gimme object')
- data = {'bar': "hello", 'baz': "world"}
- keys_list = getKeys(data)
- print(list(keys_list))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement