我有这样的字典:
fieldData = {'StreetAddress': {'type': 'string',
'valueString': '4| 7 RULE CHIE N',
'text': '4| 7 RULE CHIE N',
'page': 1,
'boundingBox': [76.0, 342.0, 829.0, 342.0, 829.0, 382.0, 76.0, 382.0],
'confidence': 1.0},
'Phone': {'type': 'string',
'valueString': '5 4 3 | 9 7 | 0 0 1',
'text': '5 4 3 | 9 7 | 0 0 1',
'page': 1,
'boundingBox': [77.0, 465.0, 648.0, 465.0, 648.0, 502.0, 77.0, 502.0],
'confidence': 1.0},
'FirstName': {'type': 'string',
'valueString': 'HENRI',
'text': 'HENRI',
'page': 1,
'boundingBox': [73.0, 291.0, 341.0, 291.0, 341.0, 322.0, 73.0, 322.0],
'confidence': 1.0},...
我需要创建一个像这样的字典:
resultsData = {'StreetAddress': '4| 7 RULE CHIE N',
'Phone': '5 4 3 | 9 7 | 0 0 1',
'FirstName': 'HENRI',
'LastName': 'AC THANICE',
'City': 'MIO N REAL',
'PostalCode': 'H 3 B O A 2',
'Province': 'Q C',
'FormId': 'C1234567',
'DonationDate': '2 6 0 6',
'Email': 'h- lach @ gmail.com',
'DonationAmount': '600.00'}
resultsData字典中的项目结合了fieldData的external_keys(即:“ StreetAddress”,“ Phone”,“ FirstName” ...)和inner_key的inner_value(如果inner_key =='text')(即:outer_key =='名字,inner_key =='文本',inner_value =='HENRI')
我已经尝试从datacamp dictionary获得基于循环的指导,>
resultsData = {} for (outer_k, outer_v) in fieldData.items(): for (inner_k, inner_v) in outer_v.items(): if inner_k == 'text': resultsData.update({outer_k:inner_v})
这将创建我正在寻找的对象(如上所述),但会引发错误:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-27-dbae6918239f> in <module> 1 resultsData = {} 2 for (outer_k, outer_v) in fieldData.items(): ----> 3 for (inner_k, inner_v) in outer_v.items(): 4 if inner_k == 'text': 5 resultsData.update({outer_k:inner_v}) AttributeError: 'NoneType' object has no attribute 'items'
我也尝试过基于Nested dictionary comprehension python中的模式的dict理解
data = {outer_key: {inner_value: inner_key for inner_value, inner_key in outer_value.items()} for outer_key, inner_value in fieldData.items()}
返回错误:
NameError Traceback (most recent call last) <ipython-input-114-c09167c38348> in <module> 1 data = {outer_key: {inner_value: inner_key for inner_value, inner_key in outer_value.items()} ----> 2 for outer_key, inner_value in fieldData.items()} <ipython-input-114-c09167c38348> in <dictcomp>(.0) 1 data = {outer_key: {inner_value: inner_key for inner_value, inner_key in outer_value.items()} ----> 2 for outer_key, inner_value in fieldData.items()} NameError: name 'outer_value' is not defined
非常感谢您提出任何解决建议。
我有这样的字典:fieldData = {'StreetAddress':{'type':'string','valueString':'4 | 7 RULE CHIE N',“ text”:“ 4 | 7 RULE CHIE N','page':1,'boundingBox':[76.0,342.0,829.0,342.0,...
一个简单的解决方案是使用字典理解,迭代所有键和值并创建一个新字典: