Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #109798 > unrolled thread

fast dictionary initialization

Started bymaurice <mauricioliveiraguarda@gmail.com>
First post2016-06-10 14:07 -0700
Last post2016-06-10 18:20 -0500
Articles 3 — 3 participants

Back to article view | Back to comp.lang.python


Contents

  fast dictionary initialization maurice <mauricioliveiraguarda@gmail.com> - 2016-06-10 14:07 -0700
    Re: fast dictionary initialization Random832 <random832@fastmail.com> - 2016-06-10 17:15 -0400
    Re: fast dictionary initialization Tim Chase <python.list@tim.thechases.com> - 2016-06-10 18:20 -0500

#109798 — fast dictionary initialization

Frommaurice <mauricioliveiraguarda@gmail.com>
Date2016-06-10 14:07 -0700
Subjectfast dictionary initialization
Message-ID<d2ee0910-1635-431e-944c-c8b4167f10c5@googlegroups.com>
Hi. If I have already a list of values, let's call it valuesList and the keysList, both same sized lists, what is the easiest/quickest way to initialize a dictionary with those keys and list, in terms of number of lines perhaps?

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}

Thanks

[toc] | [next] | [standalone]


#109799

FromRandom832 <random832@fastmail.com>
Date2016-06-10 17:15 -0400
Message-ID<mailman.142.1465593350.2306.python-list@python.org>
In reply to#109798
pOn Fri, Jun 10, 2016, at 17:07, maurice wrote:
> Hi. If I have already a list of values, let's call it valuesList and the
> keysList, both same sized lists, what is the easiest/quickest way to
> initialize a dictionary with those keys and list, in terms of number of
> lines perhaps?
> 
> 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}

dict(zip(keysList, valuesList))

[toc] | [prev] | [next] | [standalone]


#109811

FromTim Chase <python.list@tim.thechases.com>
Date2016-06-10 18:20 -0500
Message-ID<mailman.148.1465613257.2306.python-list@python.org>
In reply to#109798
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


[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web