By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,101 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

a dictionary from a list

P: n/a
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?

--
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
Jul 19 '05 #1
Share this Question
Share on Google+
16 Replies


P: n/a
dict((x, None) for x in alist)

Jul 19 '05 #2

P: n/a
David Bear wrote:
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?


You mean None, right? :)
a_list = [1, 2, 3, 'a', 'b', 'c']
dict.fromkeys(a_list)

{'a': None, 1: None, 2: None, 3: None, 'c': None, 'b': None}
--
Benji York
Jul 19 '05 #3

P: n/a
David Bear wrote:
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)
Jul 19 '05 #4

P: n/a
David Bear wrote:
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.
Jul 19 '05 #5

P: n/a
"Rocco Moretti" wrote:
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

Jul 19 '05 #6

P: n/a
On 2005-06-24, infidel <sa***********@gmail.com> wrote:
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
Jul 19 '05 #7

P: n/a
Dave Cook wrote:
On 2005-06-24, infidel <sa***********@gmail.com> wrote:

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


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
Jul 19 '05 #8

P: n/a
On Friday 24 June 2005 05:26 pm, infidel wrote:
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.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #9

P: n/a
Terry Hancock <ha*****@anansispaceworks.com> wrote:
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?
Jul 19 '05 #10

P: n/a
"Roy Smith" <ro*@panix.com> wrote:
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

Jul 19 '05 #11

P: n/a
Roy Smith wrote:
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
--
Michael Hoffman
Jul 19 '05 #12

P: n/a
Roy Smith wrote:
Terry Hancock <ha*****@anansispaceworks.com> wrote:
...
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
Sc***********@Acm.Org

Jul 19 '05 #13

P: n/a
On Sat, 25 Jun 2005 06:44:22 -0700, George Sakkis wrote:
"Roy Smith" <ro*@panix.com> wrote:
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?

--
Steven.

Jul 19 '05 #14

P: n/a
"Steven D'Aprano" wrote:
On Sat, 25 Jun 2005 06:44:22 -0700, George Sakkis wrote:
"Roy Smith" <ro*@panix.com> wrote:
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

Jul 19 '05 #15

P: n/a
[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

Jul 19 '05 #16

P: n/a
[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

Jul 19 '05 #17

This discussion thread is closed

Replies have been disabled for this discussion.