keys in dictionary

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Shi Mu

    #1

    keys in dictionary

    I run the following code and got wrong message, but I still want to
    make [1,2],[4,3] and [6,9]
    to be keys of the dictionary or change the style a little bit. How to do that?
    Thanks!
    [color=blue][color=green][color=darkred]
    >>> p=[[1,2],[4,3],[6,9]]
    >>> n=dict([(x,[]) for x in p])[/color][/color][/color]
    Traceback (most recent call last):
    File "<interacti ve input>", line 1, in ?
    TypeError: list objects are unhashable[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]
  • Martin v. Löwis

    #2
    Re: keys in dictionary

    Shi Mu wrote:[color=blue]
    > I run the following code and got wrong message, but I still want to
    > make [1,2],[4,3] and [6,9] to be keys of the dictionary or change the
    > style a little bit. How to do that?[/color]

    Make them tuples:
    [color=blue][color=green][color=darkred]
    >>> p=[[1,2],[4,3],[6,9]]
    >>> n=dict([(tuple(x),[]) for x in p])
    >>> n[/color][/color][/color]
    {(6, 9): [], (1, 2): [], (4, 3): []}

    Regards,
    Martin

    P.S. Please don't cross-post.

    Comment

    • Georges Barthelemy

      #3
      Re: keys in dictionary

      use (1,2) , (3,4)....


      "Shi Mu" <samrobertsmith @gmail.com> a écrit dans le message de news:
      mailman.987.113 2638229.18701.p ython-list@python.org...
      I run the following code and got wrong message, but I still want to
      make [1,2],[4,3] and [6,9]
      to be keys of the dictionary or change the style a little bit. How to do
      that?
      Thanks!
      [color=blue][color=green][color=darkred]
      >>> p=[[1,2],[4,3],[6,9]]
      >>> n=dict([(x,[]) for x in p])[/color][/color][/color]
      Traceback (most recent call last):
      File "<interacti ve input>", line 1, in ?
      TypeError: list objects are unhashable[color=blue][color=green][color=darkred]
      >>>[/color][/color][/color]


      Comment

      Working...