How to return dictionary keys as a list in Python?

后端 未结 8 1891
长情又很酷
长情又很酷 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条回答
  • 2020-11-22 08:30

    If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).

    newdict = {1: 0, 2: 0, 3: 0}
    *k, = newdict
    
    k
    # [1, 2, 3]
    

                ╒═══════════════╤═════════════════════════════════════════╕
                │ k = list(d)   │   9 characters (excluding whitespace)   │
                ├───────────────┼─────────────────────────────────────────┤
                │ k = [*d]      │   6 characters                          │
                ├───────────────┼─────────────────────────────────────────┤
                │ *k, = d       │   5 characters                          │
                ╘═══════════════╧═════════════════════════════════════════╛
    
    0 讨论(0)
  • 2020-11-22 08:41

    A bit off on the "duck typing" definition -- dict.keys() returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)

    In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list().

    Very similarly for zip() -- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?

    This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.

    dict.keys() should work with comprehensions, though -- check carefully for typos or something... it works fine for me:

    >>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
    >>> [key.split(", ") for key in d.keys()]
    [['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]
    
    0 讨论(0)
提交回复
热议问题