【问题标题】:Combining a nested list without affecting the key and value direction in python在python中组合嵌套列表而不影响键值方向
【发布时间】:2019-11-13 19:54:06
【问题描述】:

我有一个将数据存储在列表中的程序。 currentdesired 输出格式为:

# Current Input
[{'Devices': ['laptops', 'tablets'],
  'ParentCategory': ['computers', 'computers']},

 {'Devices': ['touch'], 'ParentCategory': ['phones']}]

# Desired Output
[{'Devices': ['laptops', 'tablets','touch'],
  'ParentCategory': ['computers', 'computers','phones']}]    

您能告诉我如何将列表与另一行 python 代码或逻辑组合以获得所需的输出吗?

【问题讨论】:

    标签: python list


    【解决方案1】:

    你可以这样做:

    def convert(a):
        d = {}
        for x in a:
            for key,val in x.items():
                if key not in d:
                    d[key] = []
                d[key] += val
        return d
    

    以上代码适用于 Python 3。

    如果您使用的是 Python 2.7,那么我认为您应该将 items 替换为 iteritems

    【讨论】:

      【解决方案2】:

      使用字典理解的解决方案:首先通过确定它应该具有哪些键来构建合并字典,然后连接每个键的所有列表。这组键和每个结果列表都是使用itertools.chain.from_iterable 构建的。

      from itertools import chain
      
      def merge_dicts(*dicts):
          return {
              k: list(chain.from_iterable( d[k] for d in dicts if k in d ))
              for k in set(chain.from_iterable(dicts))
          }
      

      用法:

      >>> merge_dicts({'a': [1, 2, 3], 'b': [4, 5]}, {'a': [6, 7], 'c': [8]})
      {'a': [1, 2, 3, 6, 7], 'b': [4, 5], 'c': [8]}
      >>> ds = [
          {'Devices': ['laptops', 'tablets'],
           'ParentCategory': ['computers', 'computers']},
          {'Devices': ['touch'],
           'ParentCategory': ['phones']}
      ]
      >>> merge_dicts(*ds)
      {'ParentCategory': ['computers', 'computers', 'phones'],
       'Devices': ['laptops', 'tablets', 'touch']}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-27
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        相关资源
        最近更新 更多