【问题标题】:Get list of common dictionaries from List of dictionaries on one key value match从一个键值匹配的字典列表中获取常用字典列表
【发布时间】:2020-03-31 14:23:30
【问题描述】:

我正在尝试根据键“host”的值将字典列表合并到列表中。相同的示例输入如下所示:

first = [{'host': '1', 'a': 'a', 'b': 'b'}, {'host': '2', 'a': 'c', 'd': 'd'}, {'host': '3', 'a': 'd', 'd': 'd'}]

second = [{'host': '1', 'a': 'w', 'b': 'e'}, {'host': '2', 'a': 'q', 'd': 's'}, {'host': '3', 'a': 'q', 'd': 'c'}]

third= [{'host': '1', 'a': 'r', 'b': 't'}, {'host': '2', 'a': 'f', 'd': 'b'}, {'host': '3', 'a': 'k', 'd': 'p'}]

我正在尝试获得这样的输出

final_list = {
  "1": [
    { "host": "1", "a": "a", "b": "b" },
    { "host": "1", "a": "w", "b": "e" },
    { "host": "1", "a": "r", "b": "t" }
  ],
  "2": [
    { "host": "2", "a": "c", "d": "d" },
    { "host": "2", "a": "q", "d": "s" },
    { "host": "2", "a": "f", "d": "b" }
  ],
  "3": [
    { "host": "3", "a": "d", "d": "d" },
    { "host": "3", "a": "q", "d": "c" },
    { "host": "3", "a": "k", "d": "p" }
  ]
}

【问题讨论】:

    标签: python python-2.7 sorting merge


    【解决方案1】:

    您希望成对压缩它们,然后使用 enumerate 对从 1 开始的对进行注释。

    final_list = {str(num): [a, b, c] for num, (a, b, c) in 
                  enumerate(zip(first, second, third), start = 1)}
    
    >>> final_list
    
    {'1': [{'a': 'a', 'b': 'b', 'host': '1'},
           {'a': 'w', 'b': 'e', 'host': '1'},
           {'a': 'r', 'b': 't', 'host': '1'}],
     '2': [{'a': 'c', 'd': 'd', 'host': '2'},
           {'a': 'q', 'd': 's', 'host': '2'},
           {'a': 'f', 'd': 'b', 'host': '2'}],
     '3': [{'a': 'd', 'd': 'd', 'host': '3'},
           {'a': 'q', 'd': 'c', 'host': '3'},
           {'a': 'k', 'd': 'p', 'host': '3'}]}
    

    【讨论】:

      【解决方案2】:

      我收集了您的列表以便于使用,您可以这样做:

      first = [{'host': '1', 'a': 'a', 'b': 'b'}, {'host': '2', 'a': 'c', 'd': 'd'}, {'host': '3', 'a': 'd', 'd': 'd'}]
      
      second = [{'host': '1', 'a': 'w', 'b': 'e'}, {'host': '2', 'a': 'q', 'd': 's'}, {'host': '3', 'a': 'q', 'd': 'c'}]
      
      third= [{'host': '1', 'a': 'r', 'b': 't'}, {'host': '2', 'a': 'f', 'd': 'b'}, {'host': '3', 'a': 'k', 'd': 'p'}]
      
      final_dict = {}
      
      allList = [first, second, third]
      
      for aList in allList:
        for aDict in aList:
          if aDict["host"] not in final_dict.keys():
            final_dict[aDict["host"]] = [aDict]
          else:
            final_dict[aDict["host"]].append([aDict])
      
      print(final_dict)
      

      【讨论】:

        猜你喜欢
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 2011-09-24
        • 2013-08-29
        • 2021-11-17
        • 2018-12-14
        • 1970-01-01
        相关资源
        最近更新 更多