【问题标题】:Not able to read the values of a key in python dictionary无法读取python字典中键的值
【发布时间】:2022-08-18 22:34:12
【问题描述】:

该代码能够读取第一个键的值,但不能读取第二个键的值。

#join_tables =  {\'table_e_input_cols\': [\' e.rowkey\', \' e.branchsequencenumber\'], \'table_e1_input_cols\': [\' e1.branchsequencenumber\', \' e1.ranchsequencenumber\']}           
i=0
for k,v in join_tables.items():
    print(table_e_input_cols[i].split(sep=\'.\'))
    print(table_e1_input_cols[i].split(sep=\'.\'))
    i = i+1

得到的错误是:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/tmp/ipykernel_31619/2960019421.py in <cell line: 20>()
     20 for k,v in join_tables.items():
     21     print(table_e_input_cols[i].split(sep=\'.\'))
---> 22     print(table_e1_input_cols[i].split(sep=\'.\'))
     23     i = i+1
     24     #print(k)

NameError: name \'table_e1_input_cols\' is not defined
  • 您的密钥是 \"v\"
  • 你为什么要遍历 dict 项目只是为了在 2 行之后直接引用它们?使用从迭代器获得的对象 - print(v[0].split(sep=\'.\')); print(v[1].split(sep=\'.\'))
  • ``` ----------------------------------------------- ---------------------------- IndexError Traceback(最近一次调用最后一次)/tmp/ipykernel_31619/2436809718.py in <cell line: 20 >() 19 i=0 20 for k,v in join_tables.items(): ---> 21 print(v[0].split(sep=\'.\')); print(v[1].split(sep=\'.\')) 22 #print(table_e_input_cols[i].split(sep=\'.\')) 23 #print(table_e1_input_cols[i].split(sep =\'.\')) IndexError: 列表索引超出范围```

标签: python


【解决方案1】:

当我尝试取消注释第一行并运行您的代码时,我收到以下错误:

NameError: name 'table_e_input_cols' is not defined

这很可能是在您的代码中较早的其他地方定义的,这就是为什么您没有收到第一个键的错误。

由于您已经在迭代键和值,因此打印出这样的值会更容易:

join_tables =  {'table_e_input_cols': [' e.rowkey', ' e.branchsequencenumber'], 'table_e1_input_cols': [' e1.branchsequencenumber', ' e1.ranchsequencenumber']}           

for k,v in join_tables.items():
    print(f"Key is {key} and value is {v}")

如果要独立迭代每个值:

join_tables =  {'table_e_input_cols': [' e.rowkey', ' e.branchsequencenumber'], 'table_e1_input_cols': [' e1.branchsequencenumber', ' e1.ranchsequencenumber']}           

for k,v in join_tables.items():
    for index, item in enumerate(v):
        print(f"Key is {key} and index {index} of value is {item}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 2014-06-11
    • 2022-11-28
    相关资源
    最近更新 更多