a dictionary from a list

D

David Bear

I know there must be a better way to phrase this so google understands, but
I don't know how.. So I'll ask people.

Assume I have a list object called 'alist'.

Is there an easy way to create a dictionary object with the members of
'alist' being the keys in the dictionary, and the value of the keys set to
null?
 
L

Leif K-Brooks

David said:
Is there an easy way to create a dictionary object with the members of
'alist' being the keys in the dictionary, and the value of the keys set to
null?

adict = dict.fromkeys(alist)
 
R

Rocco Moretti

David said:
I know there must be a better way to phrase this so google understands, but
I don't know how.. So I'll ask people.

Assume I have a list object called 'alist'.

Is there an easy way to create a dictionary object with the members of
'alist' being the keys in the dictionary, and the value of the keys set to
null?

Are you sure you need a dictionary? You may want to look at the Set
module instead, if the values aren't important.
 
G

George Sakkis

Rocco Moretti said:
Are you sure you need a dictionary? You may want to look at the Set
module instead, if the values aren't important.

Set is the name of the type in the module sets, introduced in 2.3.
Since 2.4 you can use the builtin set type. Here's the import snippet
that works for 2.3 or later:

try: set
except NameError:
from sets import Set as set

George
 
D

Dave Cook

dict((x, None) for x in alist)

Whoa, I thought dictionary comprehensions were still planned feature. I
guess I gotta start paying closer attention.

Dave Cook
 
P

Peter Hansen

Dave said:
Whoa, I thought dictionary comprehensions were still planned feature. I
guess I gotta start paying closer attention.

Added in Python 2.4, it's actually a generator expression as the sole
argument to a generic dict() constructor. Think of the generator
expression as sort of like the list comprehension that it resembles,
minus the square brackets, but which doesn't have to create the entire
list before the dict() constructor starts to consume the elements.

-Peter
 
T

Terry Hancock

dict((x, None) for x in alist)

or if you want it to run in 2.3 (before "generator
expressions"):

dict( [(x,None) for x in alist] )

Before the dict constructor, you needed to do this:

d={}
for key in alist:
d[key]=None

which is still only 3 lines and will run
in Python 1.5, IIRC.
 
R

Roy Smith

Terry Hancock said:
Before the dict constructor, you needed to do this:

d={}
for key in alist:
d[key]=None

I just re-read the documentation on the dict() constructor. Why does it
support keyword arguments?

dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"}

This smacks of creeping featurism. Is this actually useful in real code?
It took me several readings of the doc to understand what this was doing.
Essentially, it's Perl's bareword syntax, and once I realized that, I
simultaneously understood what was happening and was revolted that Python
seems to have picked up one of Perl's most bizarre and confusing features.

I also think the published description is needlessly confusing. Why does
it use

{'one': 2, 'two': 3}

as the example mapping when

{'one': 1, 'two': 2}

would illustrate exactly the same point but be easier to comprehend. The
mapping given is the kind of thing I would expect to see in an obfuscated
programming contest.

Also, what's the point of the last example:

dict([(['one', 'two'][i-2], i) for i in (2, 3)])

It boils down to passing a list of tuples as an argument, which is already
illustrated by other examples. This is just a complicated and obtuse way
to construct the list of tuples. What does it add to the understanding of
how the dict() constructor works?
 
G

George Sakkis

Roy Smith said:
I just re-read the documentation on the dict() constructor. Why does it
support keyword arguments?

dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"}

This smacks of creeping featurism. Is this actually useful in real code?
It took me several readings of the doc to understand what this was doing.
Essentially, it's Perl's bareword syntax, and once I realized that, I
simultaneously understood what was happening and was revolted that Python
seems to have picked up one of Perl's most bizarre and confusing features.

The worst thing about this form of the dict constructor it's not the
syntax; I think this becomes obvious after you've seen it once. More
annoying is that it "wastes" keyword arguments that could otherwise be
used to determine the characteristics of the dict. Perhaps the most
common desired feature is setting a default value for the dict, that
would allow for instance:

wordCount = dict(default=0)
wordPos = dict(default=[])
for pos,word in enumerate(text):
wordCount[word] += 1
wordPos[word].append(pos)

Other candidate optional arguments would allow type checking (e.g.
dict(keys=int, values=list)) or performance fine-tuning (e.g.
dict(minsize = 10, maxsize = 10000, average = 200)). I hope the
decision for this form of the constructor is reconsidered for python
3K.

George
 
M

Michael Hoffman

Roy said:
I just re-read the documentation on the dict() constructor. Why does it
support keyword arguments?

dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"}

This smacks of creeping featurism. Is this actually useful in real code?

Personally, I use it all the time. It's a much more convenient literal
for a dictionary. And before it was introduced I used this utility function:

def mkdict(**kwargs):
return kwargs
 
S

Scott David Daniels

Roy said:
...
I just re-read the documentation on the dict() constructor. Why does it
support keyword arguments?

dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"}

This smacks of creeping featurism. Is this actually useful in real code?
Yes it's useful, and it grew organically from the keyword arg syntax.
No new syntax was introduced to provide this; the existing syntax was
used.

--Scott David Daniels
(e-mail address removed)
 
S

Steven D'Aprano

Roy Smith said:
I just re-read the documentation on the dict() constructor. Why does it
support keyword arguments?

dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"}

This smacks of creeping featurism. Is this actually useful in real code?
It took me several readings of the doc to understand what this was doing.
Essentially, it's Perl's bareword syntax, and once I realized that, I
simultaneously understood what was happening and was revolted that Python
seems to have picked up one of Perl's most bizarre and confusing features.

The worst thing about this form of the dict constructor it's not the
syntax; I think this becomes obvious after you've seen it once. More
annoying is that it "wastes" keyword arguments that could otherwise be
used to determine the characteristics of the dict. Perhaps the most
common desired feature is setting a default value for the dict, that
would allow for instance:

wordCount = dict(default=0)
wordPos = dict(default=[])
for pos,word in enumerate(text):
wordCount[word] += 1
wordPos[word].append(pos)

Other candidate optional arguments would allow type checking (e.g.
dict(keys=int, values=list)) or performance fine-tuning (e.g.
dict(minsize = 10, maxsize = 10000, average = 200)). I hope the
decision for this form of the constructor is reconsidered for python
3K.

Since Python dicts don't have default values, or type-checking, or
user-editable performance fine-tuning, or for that matter any optional
arguments, it is hardly possible to "waste" keyword arguments for a
function that doesn't need any keyword arguments.

What you actually mean to say is that the use of keyword arguments as
"bareword" syntax for initialising dicts conflicts with the use of keyword
arguments for non-existent, hypothetical and/or user-defined classes.

That's okay. I'm perfectly comfortable with the fact that the syntax for
initialising a dict conflicts with the syntax for initialising a list, a
Decimal, a MutableString, and a ConfigParser object.

So why should I be distressed that it conflicts with the syntax for
initialising MyDictWithDefaultValue objects?
 
G

George Sakkis

Steven D'Aprano said:
Roy Smith said:
I just re-read the documentation on the dict() constructor. Why does it
support keyword arguments?

dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"}

This smacks of creeping featurism. Is this actually useful in real code?
It took me several readings of the doc to understand what this was doing.
Essentially, it's Perl's bareword syntax, and once I realized that, I
simultaneously understood what was happening and was revolted that Python
seems to have picked up one of Perl's most bizarre and confusing features.

The worst thing about this form of the dict constructor it's not the
syntax; I think this becomes obvious after you've seen it once. More
annoying is that it "wastes" keyword arguments that could otherwise be
used to determine the characteristics of the dict. Perhaps the most
common desired feature is setting a default value for the dict, that
would allow for instance:

wordCount = dict(default=0)
wordPos = dict(default=[])
for pos,word in enumerate(text):
wordCount[word] += 1
wordPos[word].append(pos)

Other candidate optional arguments would allow type checking (e.g.
dict(keys=int, values=list)) or performance fine-tuning (e.g.
dict(minsize = 10, maxsize = 10000, average = 200)). I hope the
decision for this form of the constructor is reconsidered for python
3K.

Since Python dicts don't have default values, or type-checking, or
user-editable performance fine-tuning, or for that matter any optional
arguments, it is hardly possible to "waste" keyword arguments for a
function that doesn't need any keyword arguments.

What you actually mean to say is that the use of keyword arguments as
"bareword" syntax for initialising dicts conflicts with the use of keyword
arguments for non-existent, hypothetical and/or user-defined classes.

That's okay. I'm perfectly comfortable with the fact that the syntax for
initialising a dict conflicts with the syntax for initialising a list, a
Decimal, a MutableString, and a ConfigParser object.

So why should I be distressed that it conflicts with the syntax for
initialising MyDictWithDefaultValue objects?

Because this specific use case at least is/was considered useful enough
to start off a thread that invited over a hundred posts on a pre-PEP
suggesting two new accumulator methods (http://tinyurl.com/aqpk3).
Default-valued dicts make the two proposed methods redundant and are a
more elegant solution to the dictionary based accumulation problem. So
yes, one can write MyDictWithDefaultValue (and I'm sure many have), but
the keyword-arg dict constructor prevents python from including it in
the future without breaking backwards compatibility.

George
 
R

Raymond Hettinger

[Roy Smith]
I also think the published description is needlessly confusing. Why does
it use

{'one': 2, 'two': 3}

as the example mapping when

{'one': 1, 'two': 2}

would illustrate exactly the same point but be easier to comprehend. The
mapping given is the kind of thing I would expect to see in an obfuscated
programming contest.

Also, what's the point of the last example:

dict([(['one', 'two'][i-2], i) for i in (2, 3)])

It boils down to passing a list of tuples as an argument, which is already
illustrated by other examples. This is just a complicated and obtuse way
to construct the list of tuples. What does it add to the understanding of
how the dict() constructor works?

If you can switch from indignation to constructive criticism, then
consider sending a note to Andrew Kuchling suggesting ways to improve
the examples.


Raymond
 
R

Raymond Hettinger

[Roy Smith]
I also think the published description is needlessly confusing. Why does
it use

{'one': 2, 'two': 3}

as the example mapping when

{'one': 1, 'two': 2}

would illustrate exactly the same point but be easier to comprehend. The
mapping given is the kind of thing I would expect to see in an obfuscated
programming contest.

Also, what's the point of the last example:

dict([(['one', 'two'][i-2], i) for i in (2, 3)])

It boils down to passing a list of tuples as an argument, which is already
illustrated by other examples. This is just a complicated and obtuse way
to construct the list of tuples. What does it add to the understanding of
how the dict() constructor works?

If you can switch from indignation to constructive criticism, then
consider sending a note to Andrew Kuchling suggesting ways to improve
the examples.


Raymond
 

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

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top