【问题标题】:Merge two list of dictionaries with same key:value in python合并两个具有相同键的字典列表:python中的值
【发布时间】:2017-04-20 05:55:27
【问题描述】:

晚上好, 如果它们具有相同的键:值,我想合并两个字典列表。它就像 SQL 中的连接。我不允许为此问题导入任何模块。

这里是一个例子:

输入:

>>> series = [
... {'s_id': 'bb', 'title': 'Breaking Bad'},
... {'s_id': 'bcs', 'title': 'Better Call Saul'}]

>>> series_characters = [
... {'c_id': 'ww', 's_id': 'bb'},
... {'c_id': 'sw', 's_id': 'bb'}, 
... {'c_id': 'sg', 's_id': 'bb'}
... {'c_id': 'sg', 's_id': 'bcs'}

输出应该是包含两个信息的字典列表:

out= [
{'s_id': 'bb', 'title': 'Breaking Bad', 'c_id': 'ww'},
{'s_id': 'bcs', 'title': 'Better Call Saul', 'c_id': 'sg'}]

我尝试过类似的东西,但我认为我的想法太复杂了,代码不起作用:

def _join(tbl1, tbl2):
    """
    Helping function to merge two tables inform of a list

    Argurments:
        tbl1 (list): list of dict's containung a table
        tbl2 (list): list of dict's containung a table
    Returns:
        back_lst (list): list, containing wanted rows of the table

    """
    back_lst = []
    for element1 in tbl1:
        for element2 in tbl2:
            for key in tbl1[element1]:
                if tbl1[element1[key]] == tbl2[element2[key]]:
                    a = tbl1[element1].copy()
                    a.update(tbl2[element2])
                    back_lst.append(a)
    return back_lst

很高兴在这里获得一些帮助。提前致谢。

【问题讨论】:

  • 在s_id bb的series_charachter中,c_id是ww ,sw, sg 那为什么只和sg合并而不是其他呢?
  • @harshil9968 好点,还应该注意如果有多个公共密钥,例如在 SQL 中,其中 tbl1.name=tbl2.name 和 tbl1.id=tbl2.id。

标签: python dictionary merge key


【解决方案1】:

鉴于您所有的键都只是您可以执行的字符串:

>>> [dict(a, **b) for a in series_characters for b in series if a['s_id'] == b['s_id']]
[{'c_id': 'ww', 's_id': 'bb', 'title': 'Breaking Bad'},
 {'c_id': 'sw', 's_id': 'bb', 'title': 'Breaking Bad'},
 {'c_id': 'sg', 's_id': 'bb', 'title': 'Breaking Bad'},
 {'c_id': 'sg', 's_id': 'bcs', 'title': 'Better Call Saul'}]​

【讨论】:

    【解决方案2】:

    你不想做tbl1[element1],假设tbl1 是一个字典列表。 element1 应该已经是您想要的字典,所以只需执行 element1.copy()。索引tbl2 也是如此。

    【讨论】:

      【解决方案3】:
      # your code goes here
      
      def joinTable( tbl1, tbl2 ):
          op = []
          if len( tbl1 )  > 0 and len( tbl2 ) > 0:
              keys = set( tbl1[0].keys()).intersection( tbl2[0].keys())
              opkeys = set( tbl1[0].keys()).union( tbl2[0].keys())
              for row1 in tbl1:
                  key1 = set( row1.keys())
                  for row2 in tbl2:
                      key2 = set( row2.keys())
                      assert key1.intersection( key2 ) == keys
                      assert key1.union( key2 ) == opkeys
                      match = True
                      for key in keys:
                          match = row1[ key] == row2[key]
                      if match:
                          d = dict()
                          for key in opkeys:
                              d[ key ] = row1[ key ]  if key in row1 else row2[key]
                          op.append( d )
          return op
      
      print joinTable( [{'s_id': 'bb', 'title': 'Breaking Bad'},{'s_id': 'bcs', 'title': 'Better Call Saul'}],[
      {'c_id': 'ww', 's_id': 'bb'},{'c_id': 'sw', 's_id': 'bb'}, {'c_id': 'sg', 's_id': 'bb'},{'c_id': 'sg', 's_id': 'bcs'}])
      

      Ideone

      它实现了SQL的join算法。类似于https://blogs.msdn.microsoft.com/craigfr/2006/08/03/merge-join/ 的东西。

      您可以进一步扩展它以喜欢特定的键和限制值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多