【问题标题】:Is it possible to make a dictionary with lists as values from a list of dictionaries, in a one line comprehension?是否可以在单行理解中将列表作为字典列表中的值制作字典?
【发布时间】:2021-07-10 20:23:04
【问题描述】:

如果我有 dicts A 的列表:

A = [{ 'a': 1, 'b': 2}, {'a': 3, 'b': 4}]

我可以制作以下字典吗:

B = {'a': [1, 3], 'b': [2, 4]}

仅使用 dict/list 理解?

奖励:我也可以解释 A 中的不同键吗?例如:

A = [{ 'a': 1, 'b': 2}, {'a': 3, 'b': 4, 'c': 5}]
B = {'a': [1, 3], 'b': [2, 4], 'c': [None, 5]}

我已经设法通过 for 循环和 if 语句来做到这一点,希望能够更快地处理

【问题讨论】:

    标签: python-3.x list dictionary


    【解决方案1】:

    试试:

    A = [{"a": 1, "b": 2}, {"a": 3, "b": 4, "c": 5}]
    
    out = {k: [d.get(k) for d in A] for k in set(k for d in A for k in d)}
    print(out)
    

    打印:

    {'a': [1, 3], 'b': [2, 4], 'c': [None, 5]}
    

    【讨论】:

    • 哇,谢谢,我要花点时间才能理解这个问题。我想一个后续问题是,如果您的主要目标是尽可能快地编写代码,您会以这种方式实现它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2019-07-28
    • 2011-03-14
    相关资源
    最近更新 更多