【问题标题】:Looping through and Accessing nested dictionary elements循环访问嵌套的字典元素
【发布时间】:2023-01-25 03:53:19
【问题描述】:

我正在尝试将字典元素附加到列表中:

test1 = pd.DataFrame
list_of_origins = []
list_of_destinations = []
for test in list_of_details_per_flight:
    
    if test['airport']['origin'] is not None:
        print(test['airport']['origin']['position'])

但是我在第四行收到以下错误:

TypeError: byte indices must be integers or slices, not str

当我检查每次迭代的类型时,它指出它是一个字典对象,因此应该可以通过它们的键访问,所以我认为我做对了。

【问题讨论】:

  • 确保您尝试使用变量test 访问的对象是字典。你能显示type(test)的输出吗?
  • 也许 test 是一本字典。但似乎 test['arirport'] 是一个字节对象。没有minimal reproducible example我们就不知道
  • 您只是在测试 test['airport']['origin'] 不是 None。是什么让您认为它是 dict 而不是 bytes
  • print(type(test['airport']['origin'])) 是一个 NoneType 类,而 class dict print(type(test['airport'])) 是一个类 dict if print(type(test['airport' ]['origin'])) 不是 NoneType 类。 type(test) 始终是类字典。
  • 请发帖list_of_details_per_flight

标签: python loops dictionary


【解决方案1】:

print(type(test['airport']))是一个班级字典如果print(type(test['airport']['origin'])) 不是一个类无类型

这是给定的,因为您需要 test['airport'] 成为字典才能访问 ['origin'] - 事实上,test['airport'] 不是字典可能是导致错误的原因。

你试过打印type(test['airport'])if 块?是吗总是一本字典?如果是,那么if test['airport']['origin']不应该引发该错误,除非 test 曾经不是字典,但您已经确认它是:

type(test) 永远是一个班级字典.


print(type(test['airport']['origin']))是一个班级无类型和类字典

如果那是总是所以,那个错误永远不会在test['airport']['origin']['position']. (这两行是您的 sn-p 中此错误的唯一可能来源。)



如果没有你使用的list_of_details_per_flight,我无法测试其中的任何一个,但我可以建议 3 种可能的方法来解决这个问题而不会引发错误:


建议一:增加条件

您可以单独检查是否可以访问 3 个键中的每一个。

for test in list_of_details_per_flight:
    for k in ['airport', 'origin', 'position']:
        if not isinstance(test, dict):
            # print(f"can't access ['{k}'] of {type(test)} {test}")
            break

        if k not in test:
            # print(f"no value for ['{k}'] in {test}")
            break
        test = test[k] ## OR JUST
        # test = test.get(k) ## [ if you want to omit the if k not in test block ]

建议 2:只需从 try 块内打印

for test in list_of_details_per_flight:
    try: print(test['airport']['origin']['position'])
    except: pass ## OR 
    # except Exception as e: print(type(e), e) # print an error msg for that test

建议3:打印所有position

我有一个 set of functions 可用于检索全部list_of_destinations 中的值与 position 作为键配对。

allPos = getNestedVal(
    list_of_destinations, nKey='position', rForm='_all', 
    pKeys=[], objName='list_of_destinations'
)

for pos in allPos: print(pos['val'], '<---', pos['expr']) 
  • 如果您只想要airport 内的origin 内的position 值,请通过pKeys=['airport', 'origin']getNestedVal(指定父键)。
  • pos['expr'] 将包含完整的密钥路径,例如list_of_destinations[0]['airport']['origin']['position']等等,但是如果你只想要所有的值,你可以通过设置将它们放在一个平面列表中rForm='just_vals_all'.

您还可以通过在 except 块中打印 test 中的所有 position 值来组合最后两个建议。

for test in list_of_details_per_flight:
    try: print(test['airport']['origin']['position'])
    except Exception as e: : pass ## OR 
        # print(type(e), e) # print an error msg for that test
        tPos = getNestedVal(test, nKey='position', rForm='_all', pKeys=[], objName='test')
        # if not tPos:  print('	This test contains no position values')
        for pos in tPos: print('	', pos['val'], '<---', pos['expr']) 
  • 如果您只需要第一个 position 值而不是所有值的列表,请删除_all来自rForm 的结尾。

笔记:getNestedVal 如果list_of_details_per_flight很大;它主要用于一次性查找深层嵌套字典中某些值的路径中的键列表,然后从那时起使用这些路径。

【讨论】:

    猜你喜欢
    • 2019-11-07
    • 1970-01-01
    • 2021-12-19
    • 2020-10-09
    • 1970-01-01
    • 2020-09-15
    • 2021-05-28
    • 2021-11-07
    • 2017-07-22
    相关资源
    最近更新 更多