Skip to content

Instantly share code, notes, and snippets.

@arangates
Last active September 4, 2019 09:43
Show Gist options
  • Save arangates/ef16159e064146ae19263e1e09623535 to your computer and use it in GitHub Desktop.
Save arangates/ef16159e064146ae19263e1e09623535 to your computer and use it in GitHub Desktop.
# <------------------------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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment