a dictionary from a list

Discussion in 'Python' started by David Bear, Jun 24, 2005.

  1. David Bear

    David Bear Guest

    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 --
     
    David Bear, Jun 24, 2005
    #1
    1. Advertising

  2. David Bear

    infidel Guest

    dict((x, None) for x in alist)
     
    infidel, Jun 24, 2005
    #2
    1. Advertising

  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)
     
    Leif K-Brooks, Jun 24, 2005
    #3
  4. David Bear

    Benji York Guest

    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
     
    Benji York, Jun 24, 2005
    #4
  5. 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.
     
    Rocco Moretti, Jun 24, 2005
    #5
  6. "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
     
    George Sakkis, Jun 25, 2005
    #6
  7. David Bear

    Dave Cook Guest

    On 2005-06-24, infidel <> 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
     
    Dave Cook, Jun 25, 2005
    #7
  8. David Bear

    Peter Hansen Guest

    Dave Cook wrote:
    > On 2005-06-24, infidel <> 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
     
    Peter Hansen, Jun 25, 2005
    #8
  9. 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
     
    Terry Hancock, Jun 25, 2005
    #9
  10. David Bear

    Roy Smith Guest

    Terry Hancock <> 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?
     
    Roy Smith, Jun 25, 2005
    #10
  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?
    > 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
     
    George Sakkis, Jun 25, 2005
    #11
  12. 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
     
    Michael Hoffman, Jun 25, 2005
    #12
  13. Roy Smith wrote:
    > Terry Hancock <> 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
     
    Scott David Daniels, Jun 25, 2005
    #13
  14. On Sat, 25 Jun 2005 06:44:22 -0700, George Sakkis wrote:

    > "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?
    >> 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.
     
    Steven D'Aprano, Jun 25, 2005
    #14
  15. "Steven D'Aprano" wrote:

    > On Sat, 25 Jun 2005 06:44:22 -0700, George Sakkis wrote:
    >
    > > "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?
    > >> 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
     
    George Sakkis, Jun 25, 2005
    #15
  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
     
    Raymond Hettinger, Jun 28, 2005
    #16
  17. [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
     
    Raymond Hettinger, Jun 28, 2005
    #17
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ilias Lazaridis
    Replies:
    6
    Views:
    484
    Ilias Lazaridis
    Feb 21, 2006
  2. james_027
    Replies:
    1
    Views:
    363
    Marc 'BlackJack' Rintsch
    Aug 22, 2007
  3. Navkirat Singh
    Replies:
    6
    Views:
    3,334
    Navkirat Singh
    Jul 29, 2010
  4. Chris Rebert
    Replies:
    0
    Views:
    573
    Chris Rebert
    Jul 29, 2010
  5. Fox

    dictionary within dictionary

    Fox, Mar 8, 2005, in forum: ASP General
    Replies:
    5
    Views:
    213
    Michael D. Kersey
    Mar 13, 2005
Loading...

Share This Page