opposite of dict.items()

T

Tertius

Is there a method to create a dict from a list of keys and a list of
values ?

TIA
Tertius
 
P

Peter Otten

Tertius said:
Is there a method to create a dict from a list of keys and a list of
values ?
{0: 'a', 1: 'b', 2: 'c'}

Not a method() but a method.

Peter
 
L

Lulu of the Lotus-Eaters

|a = {}
|for k , v in zip(keys,values):
| a[k] = v
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

--
mertz@ | The specter of free information is haunting the `Net! All the
gnosis | powers of IP- and crypto-tyranny have entered into an unholy
..cx | alliance...ideas have nothing to lose but their chains. Unite
| against "intellectual property" and anti-privacy regimes!
-------------------------------------------------------------------------
 
R

Raymond Hettinger

[Tertius wrote]
[Peter Otten]
{0: 'a', 1: 'b', 2: 'c'}


If you're using Py2.3, then the itertools way is a bit nicer:
{0: 'a', 1: 'b', 2: 'c'}


Raymond Hettinger
 
B

Berthold Hoellmann

Tertius said:
Tertius said:
Is there a method to create a dict from a list of keys and a list of
values ?
TIA
Tertius

I found a way...

a = {}
for k , v in zip(keys,values):
a[k] = v

Or:

python
Python 2.3 (#1, Jul 30 2003, 21:59:29)
[GCC 3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Greetings
Berthold
 
C

Chad Netzer

{0: 'a', 1: 'b', 2: 'c'}

If I could use the above in Py2.4, it would be even nicer, namely:

- convert itertools to builtins

The push is to have LESS builtins. You can always import them in to the
current namespace:

from itertools import izip
- add irange(), perhaps as an alias for xrange() like file/open

I suggested an irange to Raymond, and even coded one up, a while ago.
He sees it as bloat, and rightfully so, since there is a push to allow
optimizations of range that would achieve the same effect. (ie. rather
than remembering when to use range(), xrange(), or irange(), we could
just always use range() and the language would do lazy evaluation
whenever possible.) Unless that avenue turns out to be a complete dead
end, don't expect an irange().

BTW. In the example you used, you COULD use xrange(). The only problem
is that range has been extended, in 2.3, to accept longs, and xrange()
only works with ints, and Guido wants it that way (he doesn't want to
extend xrange()'s features, since it is a pain.) irange(), if it ever
appears, would presumably be fully range() compatible.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top