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

2024-05-14 01:21:45 发布

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

我有两个单独的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']]}]

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


Tags: 列表字典f2f1t1c2recc1
3条回答

这可以工作,但我不确定我是否理解您的数据结构规则。

# 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()]

你提供的样本数据给出了你想要的结果,希望能有所帮助。

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

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']]}

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

    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]}

相关问题 更多 >