代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

为什么列表作为键字典,仍然显示为元组作为键字典

  •  1
  • Cheok Yan Cheng  · 技术社区  · 14 年前

    当我定义使用列表作为键的字典时

    collections.defaultdict(list)
    

    当我把它打印出来时,它显示出它自己正在使用元组作为键。

    我能知道为什么吗?

    import collections
    
    tuple_as_dict_key = collections.defaultdict(tuple)
    tuple_as_dict_key['abc', 1, 2] = 999
    tuple_as_dict_key['abc', 3, 4] = 999
    tuple_as_dict_key['abc', 5, 6] = 888
    # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
    print tuple_as_dict_key
    
    list_as_dict_key = collections.defaultdict(list)
    list_as_dict_key['abc', 1, 2] = 999
    list_as_dict_key['abc', 3, 4] = 999
    list_as_dict_key['abc', 5, 6] = 888
    # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
    # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
    print list_as_dict_key
    
    5 回复  |  直到 14 年前
        1
  •  3
  •   Mark Ransom    14 年前

    defaultdict list_as_dict_key['abc', 7, 8]

        2
  •  1
  •   EMP    14 年前

        3
  •  1
  •   GWW    14 年前
        4
  •  0
  •   DaveP    14 年前
        5
  •  0
  •   Chris Morgan    14 年前

    defaultdict

    >>> from collections import defaultdict
    >>> d1 = collections.defaultdict(list)
    >>> d1['foo']
    []
    >>> d1['foo'] = 37
    >>> d1['foo']
    37
    >>> d1['bar']
    []
    >>> d1['bar'].append(37)
    >>> d1['bar']
    [37]
    

    >>> d2 = dict()
    >>> d2[37, 19, 2] = [14, 19]
    >>> d2
    {(37, 19, 2): [14, 19]}
    

    a a, b a:b

    >>> mylist = [1, 2, 3]
    >>> mylist[4, 5]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: list indices must be integers, not tuple
    

    4, 5