Python将字典的数量与条件连接结合起来

2024-10-01 22:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些输出(从db查询中收集)并映射到字典中键:值对db_column: value

我要合并的示例数据:

dicts1 = [ 
      {'K1': 'kval', 'L1': 'Lval', 'F1': None, 'F2': None, 'F3': 'ERR1'},
      {'K1': 'kval', 'L1': 'Lval', 'F1': None, 'F2': None, 'F3': 'ERR1'},
      {'F1': None, 'F2': None, 'F3': 'ERR2'}]

现在我想把这些字典合并成一个字典,但是F1F2F3中的值如果不是None,就应该与;连接。如果它是None,那么leve值就原样了。 理想情况下:如果special_key=('F1', 'F2', 'F3')中存在某个键,则连接。。在

^{pr2}$

根据在:Python - Combine two dictionaries, concatenate string values?中提出的问题,我想出了一段代码,结果搞砸了

def concat_dict(*dicts):
    keys = set().union(*dicts)
    print "keys: ", keys
    outdict = {}
    for k in keys:
        print "key: ", k
        for dic in dicts:
            print k, dic.get(k)
            outdict[k] = dic.get(k)

感谢任何帮助。在


Tags: nonel1db字典k1keysf2f1
2条回答

这就是你要找的吗?在

dicts1 = [
      {'K1': 'kval', 'L1': 'Lval', 'F1': None, 'F2': None, 'F3': 'ERR1'},
      {'K1': 'kval', 'L1': 'Lval', 'F1': None, 'F2': None, 'F3': 'ERR1'},
      {'F1': None, 'F2': None, 'F3': 'ERR2'}]

special_keys = ['F1', 'F2', 'F3']

def concat_dict(dicts1):
    outdict = {}
    for dictionary in dicts1:
        for key, value in dictionary.items():
            #FOr special keys
            if key in special_keys:
                #Check first if key is already inserted in outdict
                if key not in outdict or not outdict[key]:
                    outdict[key] = value
                #Else only if value is not None, do concatenation
                elif value:
                    outdict[key] = '{prepend};{newValue}'.format(prepend=outdict[key], newValue=value)
            else:
                outdict[key] = value

    return outdict

输出

^{pr2}$

首先,concat不返回新的dict或修改现有的dict,所以您不会得到任何东西。在

其次,您需要传入特殊密钥列表。在

第三,你需要决定如何处理钥匙。目前concat_dict正在根据顺序覆盖它所得到的任何值。不管键是否特殊,您都希望保留非空值。在

下面的函数将得到您想要的,但我并不认为它是最佳的。如果需要更多的定制,可以传递另一个函数来定制如何处理特殊键。在

def concat_dict(special_keys, *dicts):
    keys = set().union(*dicts)
    outdict = {}
    for k in keys:
        for dic in dicts:
            if dic.has_key(k):
                if k in special_keys:
                    if outdict.has_key(k) and dic[k] is not None:
                        outdict[k] = outdict[k] + ";" + dic[k]
                    else:
                        outdict[k] = dic[k]
                else:
                    outdict[k] = dic.get(k)
    return outdict

相关问题 更多 >

    热门问题