我有一些输出(从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'}]
现在我想把这些字典合并成一个字典,但是F1
,F2
,F3
中的值如果不是None
,就应该与;
连接。如果它是None
,那么leve值就原样了。
理想情况下:如果special_key=('F1', 'F2', 'F3')
中存在某个键,则连接。。在
根据在: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)
感谢任何帮助。在
这就是你要找的吗?在
输出
^{pr2}$首先,concat不返回新的dict或修改现有的dict,所以您不会得到任何东西。在
其次,您需要传入特殊密钥列表。在
第三,你需要决定如何处理钥匙。目前concat_dict正在根据顺序覆盖它所得到的任何值。不管键是否特殊,您都希望保留非空值。在
下面的函数将得到您想要的,但我并不认为它是最佳的。如果需要更多的定制,可以传递另一个函数来定制如何处理特殊键。在
相关问题 更多 >
编程相关推荐