473,408 Members | 2,832 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

a dictionary from a list

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
16 1676
dict((x, None) for x in alist)

Jul 19 '05 #2
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
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
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
"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
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
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
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
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
"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
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
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
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
"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
[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
[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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: John Mudd | last post by:
I must be missing something here. It's clearly faster to lookup an item directly in a dictionary than to scan through a list. So when I have a large lookup table I always load it in the form of a...
14
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a...
6
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: ...
4
by: O.B. | last post by:
I need the ability to parse through the values of a Dictionary and remove certain ones depending on their attribute values. In the example below, an InvalidOperationException is thrown in the...
7
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list...
0
by: xpding | last post by:
Hello, I have a class MyEmbededList contains a generic dictionary, the value field is actually the MyEmbededList type as well. There is another class need to access and manipulate a list of...
11
by: Dan Upton | last post by:
This might be more information than necessary, but it's the best way I can think of to describe the question without being too vague. The task: I have a list of processes (well, strings to...
0
by: Gary Herron | last post by:
Dan Upton wrote: Yes. Create a list of keys, and loop through it: pids = procs_dict.keys() for pid in pids: if procs_dict.poll() != None # do the counter updates del procs_dict Then the...
18
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I've a question regarding dictionaries. I have an array elements that I created, and I'm trying to sort those elements into various sections. Here's the template of my...
1
by: sachin2 | last post by:
I am using 3 types of dictionaries. 1) Dictionary<string, string > d = new Dictionary<string, string>(); 2) Dictionary<string, List<string>> d = new Dictionary<string, List<string>>(); 3)...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.