How to return dictionary keys as a list in Python?

后端 未结 8 1879
长情又很酷
长情又很酷 2020-11-22 07:42

In Python 2.7, I could get dictionary keys, values, or items as a list:

>>> newdict = {1:0, 2:0, 3:0}
>>&g         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 08:14

    I can think of 2 ways in which we can extract the keys from the dictionary.

    Method 1: - To get the keys using .keys() method and then convert it to list.

    some_dict = {1: 'one', 2: 'two', 3: 'three'}
    list_of_keys = list(some_dict.keys())
    print(list_of_keys)
    -->[1,2,3]
    

    Method 2: - To create an empty list and then append keys to the list via a loop. You can get the values with this loop as well (use .keys() for just keys and .items() for both keys and values extraction)

    list_of_keys = []
    list_of_values = []
    for key,val in some_dict.items():
        list_of_keys.append(key)
        list_of_values.append(val)
    
    print(list_of_keys)
    -->[1,2,3]
    
    print(list_of_values)
    -->['one','two','three']
    

提交回复
热议问题