代码之家  ›  专栏  ›  技术社区  ›  Wayne Werner

用序列中的列表值创建字典的最干净(最Python化)方法是什么?

  •  2
  • Wayne Werner  · 技术社区  · 11 年前

    我有一个收藏,看起来像这样:

    stuff = [('key1', 1), ('key2', 2), ('key3', 3), 
             ('key1', 11), ('key2', 22), ('key3', 33),
             ('key1', 111), ('key2', 222), ('key3', 333),
             ]
    # Note: values aren't actually that nice. That would make this easy.
    

    我想把它变成一本看起来像这样的字典:

    dict_stuff = {'key1': [1, 11, 111],
                  'key2': [2, 22, 222],
                  'key3': [3, 33, 333],
                  }
    

    转换此数据的最佳方法是什么?首先想到的方法是:

    dict_stuff = {}
    for k,v in stuff:
        dict[k] = dict.get(k, [])
        dict[k].append(v)
    

    这是最干净的方法吗?

    3 回复  |  直到 11 年前
        1
  •  2
  •   thefourtheye    11 年前

    你可以利用 dict.setdefault ,像这样

    dict_stuff = {}
    for key, value in stuff:
        dict_stuff.setdefault(key, []).append(value)
    

    它说,如果 key 字典中不存在,则使用第二个参数作为其默认值,否则返回与 钥匙 .

    我们还内置了 dict 类,它可以帮助您处理这样的情况,称为 collections.defaultdict .

    from collections import defaultdict
    dict_stuff = defaultdict(list)
    for key, value in stuff:
        dict_stuff[key].append(value)
    

    这里,如果 钥匙 中不存在 defaultdict 对象,传递给 默认词典 构造函数将被调用以创建value对象。

        2
  •  1
  •   Rafael Barros jcomeau_ictx    11 年前

    有 defaultdict 在 collections 库。

    >>> from collections import defaultdict
    >>> dict_stuff = defaultdict(list) # this will make the value for new keys become default to an empty list
    >>> stuff = [('key1', 1), ('key2', 2), ('key3', 3), 
    ...          ('key1', 11), ('key2', 22), ('key3', 33),
    ...          ('key1', 111), ('key2', 222), ('key3', 333),
    ...          ]
    >>> 
    >>> for k, v in stuff:
    ...     dict_stuff[k].append(v)
    ... 
    >>> dict_stuff
    defaultdict(<type 'list'>, {'key3': [3, 33, 333], 'key2': [2, 22, 222], 'key1': [1, 11, 111]})
    
        3
  •  0
  •   thefourtheye    11 年前
    stuff_dict = {}
    for k, v in stuff:
        if stuff_dict.has_key(k):
            stuff_dict[k].append(v)
        else:
            stuff_dict[k] = [v]
    
    
    print stuff_dict
    {'key3': [3, 33, 333], 'key2': [2, 22, 222], 'key1': [1, 11, 111]}