【发布时间】:2021-05-28 07:54:24
【问题描述】:
我正在尝试访问字典中键的嵌套元素,但每次尝试遍历它们时都会挂断。
我尝试了扁平化字典并尝试了对元素的各种索引访问器,但没有成功。
目标:访问各个元素,例如:
print(flat['_items'][0]['items']['timestamp'])
print(flat['_items'][0]['items']['value'])
下面是我尝试访问的代码、数据和元素。
def flatten_dict(dd, separator='_', prefix=''):
return { prefix + separator + k if prefix else k : v
for kk, vv in dd.items()
for k, v in flatten_dict(vv, separator, kk).items()
} if isinstance(dd, dict) else { prefix : dd }
# Attempt to Flatten the Dictinary
flat = flatten_dict(regDataDict)
for k in flat.keys():
print(k)
for k, v in flat.items():
print(k, v)
print(flat['_items'][0]['items']['timestamp']) # TypeError: string indices must be integers
print(flat['_items'][0]) # Prints all Dictionary Keys and Values
print(flat['_items']) # Prints all Dictionary Keys and Values
print(flat['_items']['{items}']) # TypeError: string indices must be integers
字典结构
_items = [
{'items': [{'errors': None,
'good': True,
'questionable': False,
'substituted': False,
'timestamp': '2021-02-01T21:40:00Z',
'value': -180.625427,
'web_exception': None}],
'links': {'source': 'https://I1DPOGpIXSBWLkGcEkjIvyMegw8PMMAA'},
'web_id': 'I1DPOGpIXSBWLkGcEkjIvyMegw8PMMAA'},
{'items': [{'errors': None,
'good': True,
'questionable': False,
'substituted': False,
'timestamp': '2021-02-01T21:40:00Z',
'value': 59.99268,
'web_exception': None}],
'links': {'source': 'https://I1DPOGpIXSBWLkGcEkjIvyMegw7_MMAA'},
'web_id': 'I1DPOGpIXSBWLkGcEkjIvyMegw7_MMAA'},
{'items': [{'errors': None,
'good': True,
'questionable': False,
'substituted': False,
'timestamp': '2021-02-01T21:39:56.055191Z',
'value': 304.8489,
'web_exception': None}],
'links': {'source': 'https://I1DPOGpIXSBWLkGcEkjIvyMegwuMYIAA'},
'web_id': 'I1DPOGpIXSBWLkGcEkjIvyMegwuMYIAA'}
]
【问题讨论】:
标签: python dictionary collections nested