【问题标题】:Convert from list of list to dictionary based on the first element of the list根据列表的第一个元素从列表列表转换为字典
【发布时间】:2022-07-10 05:33:43
【问题描述】:

我在学习 Python 时遇到了一个问题:根据某个键将列表列表转换为字典。

如果输入是:[['key1','h1'],['key2','h2'],['key3','h3'],['key1','h4'],['key1','h5'], ['key2','h6']]

输出为:{'key1':{'h1','h4','h5'}, 'key2':{'h2', 'h6'}, 'key3':{'h3'}}

逻辑是,内部数组的第一个元素被认为是新字典的键。 我目前正在通过迭代整个列表来以肮脏的方式进行操作。但是,有没有更好的方法呢?

【问题讨论】:

    标签: python-3.x list dictionary


    【解决方案1】:

    您必须遍历列表。一种方法是使用dict.setdefault

    out = {}
    for k,v in lst:
        out.setdefault(k, set()).add(v)
    

    这与下面的条件循环相同:

    out = {}
    for k,v in lst:
        if k in out:
            out[k].add(v)
        else:
            out[k] = {v}
    

    输出:

    {'key1': {'h1', 'h4', 'h5'}, 'key2': {'h2', 'h6'}, 'key3': {'h3'}}
    

    【讨论】:

      猜你喜欢
      • 2018-10-08
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多