繁体   English   中英

组合具有相同键名的 Python 字典

[英]Combine Python dictionaries that have the same Key name

我有两个单独的 Python 列表,它们在各自的字典中有共同的键名。 第二个名为recordList的列表有多个具有相同键名的字典,我想附加第一个列表clientList 以下是示例列表:

clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]

所以最终结果将是这样的,因此记录现在位于clientList内的多个字典的新列表中。

 clientList = [{'client1': [['c1','f1'], [{'rec_1':['t1','s1']},{'rec_2':['t2','s2']}]]}, {'client2': [['c2','f2']]}]

看起来很简单,但我正在努力寻找一种方法来使用变量迭代这两个字典以找到它们匹配的位置。

当您确定时,两个字典中的键名相同:

    clientlist = dict([(k, [clientList[k], recordlist[k]]) for k in clientList])

像这儿:

    >>> a = {1:1,2:2,3:3}
    >>> b = {1:11,2:12,3:13}
    >>> c = dict([(k,[a[k],b[k]]) for k in a])
    >>> c
    {1: [1, 11], 2: [2, 12], 3: [3, 13]}

假设您想要一个与两个列表中的每个键对应的值列表,请尝试以下操作:

from pprint import pprint

clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]
clientList.extend(recordList)

outputList = {}

for rec in clientList:
    k = rec.keys()[0]
    v = rec.values()[0]
    if k in outputList:
        outputList[k].append(v)
    else:
        outputList[k] = [v,]

pprint(outputList)

它会产生这个:

{'client1': [['c1', 'f1'], {'rec_1': ['t1', 's1']}, {'rec_2': ['t2', 's2']}],
 'client2': [['c2', 'f2']]}

这可能有效,但我不确定我是否理解您的数据结构规则。

# join all the dicts for better lookup and update
clientDict = {}
for d in clientList:
    for k, v in d.items():
        clientDict[k] = clientDict.get(k, []) + v

recordDict = {}
for d in recordList:
    for k, v in d.items():
        recordDict[k] = recordDict.get(k, []) + [v]

for k, v in recordDict.items():
    clientDict[k] = [clientDict[k]] + v

# I don't know why you need a list of one-key dicts but here it is
clientList = [dict([(k, v)]) for k, v in clientDict.items()]

使用您提供的示例数据,这给出了您想要的结果,希望它有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM