打印字典时出现问题

问题描述 投票:-3回答:3

我想逐行打印下面的字典,其中第二行应该是列表本身(在Python 2x中):

dict = {1: [10, 20, 30], 2: [40, 50]}
for i in dict:
    print ("i = %s" % i)
    for j in dict[i]:
        print dict[i][j]
    print ("\n")

这是通过遵循这个answer但仍然有这个错误说超出范围!!

i = 1
Traceback (most recent call last):
  File "./t.py", line 26, in <module>
    print dict[i][j]
IndexError: list index out of range

我自己在学习Python。如果这个问题对大多数人来说都是微不足道的,我道歉。

python index-error
3个回答
0
投票

只需将dict[i][j]更改为j

也不要使用变量作为dict

d = {1: [10, 20, 30], 2: [40, 50]}
for i in d:
    print ("i = %s" % i)
    for j in d[i]:
        print j
    print ("\n")

输出:

C:\Users\dinesh_pundkar\Desktop>python dsp.py
i = 1
10
20
30


i = 2
40
50



C:\Users\dinesh_pundkar\Desktop>

0
投票

您使用列表值作为列表中的索引。相反,只需打印值:

dict = {1: [10, 20, 30], 2: [40, 50]}
for i in dict:
    print ("i = %s" % i)
    for j in dict[i]:
        print j
    print ("\n")

0
投票

The list is just the value returned for the key...

首先,不要“隐藏”保留字(例如,使用'dict'作为变量名称。)

其次,您要打印的列表只是为所提供的密钥返回的值。您的示例代码在列表上进行迭代,然后使用结果值作为索引,而不是。

以下代码最接近您的示例,该示例执行您希望它执行的操作:

d = {1: [10, 20, 30], 2: [40, 50]}  
for i in d:  
  print ("i = %s" % i)  
  print d[i]  

这会在交互式Python会话中产生以下结果:

>>> d = {1: [10, 20, 30], 2: [40, 50]}  
>>> for i in d:  
...   print ("i = %s" % i)  
...   print d[i]  
... 
i = 1
[10, 20, 30]
i = 2
[40, 50]  
>>>  

更严格的实现可能如下所示:

d = {1: [10, 20, 30], 2: [40, 50]}  
for k,v in d.items():  
  print ("i = %s\n%s" % (k,v))  

这又在交互式Python会话中产生以下结果:

>>> d = {1: [10, 20, 30], 2: [40, 50]}  
>>> for k,v in d.items():  
...   print ("i = %s\n%s" % (k,v))  
... 
i = 1
[10, 20, 30]
i = 2
[40, 50]
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.