简体   繁体   中英

Issue when printing dictionary

I want to print the following dictionary line by line where the second line should be the list itself (in 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")

This is by following this answer but still having this error that said out of range!!

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

I am learning Python by myself. I apologize if this question is trivial to most of you.

Just change dict[i][j] to only j

Also don't use variable as 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")

Output:

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


i = 2
40
50



C:\Users\dinesh_pundkar\Desktop>

You used your list values as indices into the list. Instead, just print the value:

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")

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

First, don't 'hide' reserved words (by using 'dict' as a variable name, for instance.)

Second, the list you wish to print is just the value returned for the key provided. Your sample code is iterating over the list and then using the resultant value as an index, which it is not.

The following code is the closest to your example that does what you described you wanted it to do:

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

Which yields the following in an interactive Python session:

>>> 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]  
>>>  

A tighter implementation might look like this:

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

Which, again, yields the following in an interactive Python session:

>>> 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]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM