Pergunta

index = {
    u'when_air': 0,
    u'chrono': 1,
    u'age_marker': 2,
    u'name': 3
}

How can I make this more beautiful (and clear) way than just manually setting each value?

like:

index = dict_from_range(
    [u'when_air', u'chrono', u'age_marker', u'name'],
    range(4)
)
Foi útil?

Solução

You can feed the results of zip() to the builtin dict():

>>> names = [u'when_air', u'chrono', u'age_marker', u'name']
>>> print(dict(zip(names, range(4))))
{'chrono': 1, 'name': 3, 'age_marker': 2, 'when_air': 0}

zip() will return a list of tuples, where each tuple is the ith element from names and range(4). dict() knows how to create a dictionary from that.

Notice that if you give sequences of uneven lengths to zip(), the results are truncated. Thus it might be smart to use range(len(names)) as the argument, to guarantee an equal length.

>>> print(dict(zip(names, range(len(names)))))
{'chrono': 1, 'name': 3, 'age_marker': 2, 'when_air': 0}

Outras dicas

You can use a dict comprehension together with the built-in function enumerate to build the dictionary from the keys in the desired order.

Example:

keys = [u'when_air', u'chrono', u'age_marker', u'name']
d = {k: i for i,k in enumerate(keys)}
print d

The output is:

{u'age_marker': 2, u'when_air': 0, u'name': 3, u'chrono': 1}

Note that with Python 3.4 the enum module was added. It may provide the desired semantics more conveniently than a dictionary.


For reference:

index = {k:v for k,v in zip(['when_air','chrono','age_marker','name'],range(4))}

This?

#keys = [u'when_air', u'chrono', u'age_marker', u'name']

from itertools import count
print dict(zip(keys, count()))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top