简体   繁体   中英

get dictionary enumerate as list

I tried to get result of the enumerate as list.

I tried as follows

D = {'red': '#FF0000',
 'lime': '#00FF00',
 'blue': '#0000FF'}

print (D)

for key, value in D.items():
    print (key, value)

print (list(D.keys()))
print (list(enumerate(D.keys())))

{'red': '#FF0000', 'lime': '#00FF00', 'blue': '#0000FF'}
red #FF0000
lime #00FF00
blue #0000FF
['red', 'lime', 'blue']
[(0, 'red'), (1, 'lime'), (2, 'blue')]

The result should be :

[0,1,2].

How to get [0,1,2] from D?

Enumerate gives you tuples as (index, value) so you would new to unpack those:

enumeration = [i for i, k in enumerate(D.keys())]

For interest, range is faster:

from timeit import timeit

D = {'red': '#FF0000', 'lime': '#00FF00', 'blue': '#0000FF'}

def e(d=D):
    return [i for i, _ in enumerate(d.keys())]

def r(d=D):
    return list(range(len(d)))

def e_gen(d=D):
    return (i for i, _ in enumerate(d.keys()))

def r_gen(d=D):
    return range(len(d))

methods = [r, e, r_gen, e_gen]
for m in methods:
    print("{}\t{:.10f}s".format(m, timeit(m, number=100) / 100))

# <function r at 0x105715488>       0.0000010044s
# <function e at 0x10551d1e0>       0.0000013061s
# <function r_gen at 0x1059f7ae8>   0.0000006587s
# <function e_gen at 0x105678488>   0.0000014094s

基于疯狂物理学家的评论:

print([x for x in range(len(D))])

If you just want to get [0, 1, 2] , then you can just use the range over the length of the dictionary:

>>> list(range(len(D)))
[0, 1, 2]

Note that those indexes will not help you at all when you are trying to access the dictionary. Dictionary entries are always pairs of keys and values, and you will have to use an actual key to access the value in the dictionary.

That's why when you iterate over the dictionary, you are essentially iterating over its keys:

>>> for key in D:
        print(key, D[key])

red #FF0000
lime #00FF00
blue #0000FF

Alternatively, you can also iterate over the items of the dictionary which will give you the key and its value at the same time:

>>> for (key, value) in D.items():
        print(key, value)

red #FF0000
lime #00FF00
blue #0000FF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM