python - 我如何使用 python 中的字典组合其他列表中项目的所有值?

标签 python dictionary

我有两个列表,需要将它们组合成一个字典,键是字母,值是另一个列表中的值。 例如:

map_keys_to_values_list(["a", "b", "a"], [15, 3, 6])

会给我:

{'a': [15, 6], 'b': [3]}

我试过:

def keys_to_values_list(k_lst, v_lst):
    lst = []
    for i in range(len(k_lst)):
        v=[]
        #v.append(v_lst[i])
        t = (k_lst[i],v)
        lst.append(t)
    my_dict = dict(lst)
    for k in my_dict.keys():
        val = my_dict.get(k)
        for m in range(len(k_lst)):
            val.append(v_lst[m])


    return my_dict

但我得到了值列表中的所有值

最佳答案

您可以使用 collections.defaultdict将默认工厂作为 list 传递以收集属于同一字符的所有值:

from collections import defaultdict

def map_keys_to_values_list(keys, values):
    d = defaultdict(list)
    for k, v in zip(keys, values):
        d[k].append(v)
    d.default_factory = None
    return d

构建字典后,您可以将字典的default_factory设置为None,这样进一步的键访问不会为丢失的键生成新的列表,而是会引发更合适的KeyError:

>>> d = map_keys_to_values_list(["a", "b", "a"], [15, 3, 6])
>>> d
defaultdict(None, {'a': [15, 6], 'b': [3]})
>>> d['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'

关于python - 我如何使用 python 中的字典组合其他列表中项目的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364340/

相关文章:

c++ - 遇到内存泄漏问题 - 在 std::map 中重新绑定(bind)键

c# - 我应该在 Web API 2 中将哪种形式的 JSON 与 Dictionary<string,string> 一起使用?

python - 如何在 SQLAlchemy 中查询关联表?

python - ISIN 函数不适用于日期

python - mysql-python 连接器同时适用于 python2.7 和 3.4

python - 查找两位数python结果的程序

c++ - 如何在 STL map 上使用 binary_search

python - 为什么我们在 Python 字典生成器中会有这种行为?

C# LINQ 获取字典计数

python - 多个子域,通用路由模式