def keys(dic):
return [key for key in dic]
print(keys(dic))
I want to replace list comprehension to for loop
CodePudding user response:
def f(dic):
new_keys = []
for i in dic:
new_keys.append(i)
return new_keys
def g(dic):
return list(dic)
def h(dic):
return [*dic]
dic = {'a': 1, 'b': 2}
print(f(dic))
print(g(dic))
print(h(dic))
f does what you want, but I wouldn't use f. I would go with g, and maybe take a look on h. h is for python >= 3.5. Check here for more details: How to return dictionary keys as a list in Python?
Check the output
['a', 'b']
['a', 'b']
['a', 'b']
CodePudding user response:
Is this what you require?
def keys(dic):
key_list = []
for key in dic.keys():
list.append(key)
print(key)
return key_list