fast dictionary initialization
Tim Chase
python.list at tim.thechases.com
Fri Jun 10 19:20:14 EDT 2016
On 2016-06-10 14:07, maurice wrote:
> example:
> valuesList = [1,2,3]
> keysList = ['1','2','3']
>
> So the dictionary can basically convert string to int:
>
> dictionary = {'1':1, '2':2, '3':3}
A couple similar options:
The most straightforward translation of your description:
opt1 = dict(zip(keysList, valuesList))
print(opt1["2"])
And one where you generate the strings on the fly:
opt2 = dict((str(i), i) for i in range(1, 4))
print(opt2["2"])
And one where you use the int() function instead of a mapping because
the whole idea of storing a dict worth of string-numbers-to-numbers
seems somewhat silly to me:
print(int("2"))
-tkc
More information about the Python-list
mailing list