Python - 匹配具有相似键值对的字典

Python - Matching dictionaries with similar key-value pair

我正在尝试使用 line texts 的键 y2 来匹配字典,并将它们存储在新的字典键 Transaction.

这是我的输入:

a = [[{'Line No ': '1', 'Line Bounding Box ': '(15, 2, 170, 79)', 'Lowest Confidence ': '0', 'Line texts ': [{'Column_No': '2', 'text_item': 'stuff1','y2':100}]}],[{'Line No ': '1', 'Line Bounding Box ': '(15, 2, 170, 79)', 'Lowest Confidence ': '0', 'Line texts ': [{'Column_No': '1', 'text_item': 'stuff2','y2':100}]}],[{'Line No ': '1', 'Line Bounding Box ': '(15, 2, 170, 79)', 'Lowest Confidence ': '0', 'Line texts ': [{'Column_No': '5', 'text_item': 'stuff3','y2':101}]}]]

这是我用过的逻辑:

sorted_lst = []

''' Getting each dict row by row '''
for i in a:
    #print(i)
    x = (i[0]['y2'])
    #print(x)
    sorted_lst.append(x)
    #print(sorted_lst)
    sorted_lst = sorted(list(set(sorted_lst)))
    c = []
    for k in sorted_lst:
        temp_dict1 = {}
        if x == k:
            temp_key1 = "column" + i[0]["Column_No"]
            temp_dict1[temp_key1] = i[0]["text_item"]
            #print(temp_dict1)
        c.append({'y2':k,'Transactions':temp_dict1})
from pprint import pprint

pprint(c)

这是当前输出,它为第一个匹配字典打印空值:

[{'Transactions': {}, 'y2': 100},
 {'Transactions': {'column5': 'stuff3'}, 'y2': 101}]

这是期望的输出:

[{'Transactions': {'column2': 'stuff1',
                   'column1': 'stuff2'},
  'y2': 100},
 {'Transactions': {'column5': 'stuff3'},
  'y2': 101}]

我的逻辑到底哪里出了问题?

考虑到 a 中的列表项只有一个字典作为其对应项,我们可以先将所有不同的 y2 值附加到列表中,然后检查遍历列表 a 在字典内的 'Line texts ' 键内搜索 y2 键的值作为列表内列表的唯一项 'a'.

试试这个:

a = [[{'Line No ': '1', 'Line Bounding Box ': '(15, 2, 170, 79)', 'Lowest Confidence ': '0', 'Line texts ': [{'Column_No': '2', 'text_item': 'stuff1','y2':100}]}],[{'Line No ': '1', 'Line Bounding Box ': '(15, 2, 170, 79)', 'Lowest Confidence ': '0', 'Line texts ': [{'Column_No': '1', 'text_item': 'stuff2','y2':100}]}],[{'Line No ': '1', 'Line Bounding Box ': '(15, 2, 170, 79)', 'Lowest Confidence ': '0', 'Line texts ': [{'Column_No': '5', 'text_item': 'stuff3','y2':101}]}]]
b = []
for i in a:
    b.append(i[0]["Line texts "][0]['y2'])
b = sorted(list(set(b)))
print(b) # [100, 101]
c = []
for k in b:
    temp_dict ={}
    for i in a:
        if i[0]["Line texts "][0]['y2'] == k:
            temp_key = "column" + str(i[0]["Line texts "][0]["Column_No"])
            temp_dict[temp_key] = i[0]["Line texts "][0]["text_item"]
    c.append({"Transactions" : temp_dict, "y2" : k})
print(c)
"""
[{'Transactions': {'column1': 'stuff2', 'column2': 'stuff1'}, 'y2': 100},
 {'Transactions': {'column5': 'stuff3'}, 'y2': 101}]
"""

您的代码应该给出 KeyError 至于 a 的列表项是单个字典的另一个列表作为没有任何键的项目 'y2',但您正在尝试访问更大字典的不存在的键。