我想通过比较python中的两个dict项来获取数据:
格言1:
rawdata = {
"node1":["id1",["set1a"]],
"node2":["id2",["set1b"]]
}
格言2:
subdata = {
"info1":["set1a","id1","firstset","firstsection"]
"info2":["set1b","id2","secondset","secondsection"]
}
可以看出,原始数据具有子数据值,但没有完整的信息。我想将dict1与dict2进行比较,以获得完整的详细信息,并将输出打印到另一个字典中,如:
"node1":"id1","set1a","firstset","firsstsection",
"node2":"id2","set1b","secondset","secondsection"
通过使用prettytable,我想以表格格式打印从最终字典中提取的信息。有人能帮我解决这个问题吗。
这可以通过dict理解来完成,但为了可读性,让我们在循环中进行:(
for rdk, rdv in rawdata.items():
sdv = next((x for x in subdata.values() if x[1] == rdv[0]))
outd[rdk] = [sdv[1], sdv[0], sdv[2], sdv[3]]
我试图让它更通用:
from pprint import pprint
rawdata = {
"node1": ["id1", ["set1a"]],
"node2": ["id2", ["set1b"]]
}
subdata = {
"info1": ["set1a", "id1", "firstset", "firstsection"],
"info2": ["set1b", "id2", "secondset", "secondsection"]
}
res = {}
for k, v in rawdata.items():
# retrieve the ID
id_ = v[0]
# Check that in 'subdata'
for k1, v1 in subdata.items():
if id_ in v1:
# Because in next line we want to get all of 'subdata' values all together.
v1.remove(id_)
res[k] = (id_, *v1)
# Make subsequent searches efficient by not researching same keys
del subdata[k1]
break
pprint(res)
输出:
{'node1': ('id1', 'set1a', 'firstset', 'firstsection'),
'node2': ('id2', 'set1b', 'secondset', 'secondsection')}