-1
def keys(dic):
    return [key for key in dic]


print(keys(dic))

I want to replace list comprehension to for loop

Henry Ecker
  • 31,792
  • 14
  • 29
  • 50

2 Answers2

0
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']
Gabriel Pellegrino
  • 1,002
  • 1
  • 7
  • 16
0

Is this what you require?

def keys(dic):
    key_list = []

    for key in dic.keys():
        list.append(key)
        print(key)

    return key_list
Shivam Roy
  • 1,848
  • 3
  • 8
  • 22