2

I wrote a dict:

msgs = {"msg_1" : "a", "msg_2" : "b", "msg_3" : "c"}

now I don't want to read in the dict manually, because I don't know how many elements will be in there (I read the dict from a file):

z = "msg_{j}"
for i in range(1, len(msgs) - 1):
    y = z.format(j=i) # This makes it "msg_1", "msg_2", "msg_3", ...
    print(msgs[y])

This throws a KeyError: msg_1. If I print out one-by-one it works just fine:

print(msgs["msg_1"])
print(msgs["msg_2"])
print(msgs["msg_3"])

... a
... b
... c

Any idea what the reason is? Why is this the case?

I tested all the functions and everything work just fine, until I get to the part with the loop (and if I use print() instead of the loop it works fine).

J.Horr
  • 117
  • 1
  • 13
  • 2
    The code you have shown seems to have resolved the issue you have in your actual code. On another note, `range(1, len(msgs)-1)` would only only iterate through 1 item - because range stops at `n-1`, So you need `range(1, len(msgs)+1)` – karthikr Dec 02 '16 at 15:42

5 Answers5

1

You'd want to iterate over your dictionary.

For Python 2.x:

for key, value in msgs.iteritems():

For Python 3.x:

for key, value in msgs.items():

More details can be found here.

Community
  • 1
  • 1
SarTheFirst
  • 350
  • 1
  • 11
1

In your case, replace len(msgs) - 1 with len(msgs) + 1,

msgs = {"msg_1" : "a", "msg_2" : "b", "msg_3" : "c"}

z = "msg_{j}"
for i in range(1, len(msgs) + 1):
    y = z.format(j=i) # This makes it "msg_1", "msg_2", "msg_3", ...
    print(msgs[y])


# Output
a
b
c
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
1

I think your are missing the .keys() method of dict object. It returns a list of all keys in the dict object.

for key in msgs.keys():
    print msgs[key]
sid-m
  • 1,504
  • 11
  • 19
0

Check out the solution from SarTheFirst. If you want to print in sorted order:

for key in sorted(msg):
    print(msgs[key])
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • 1
    This may not be sorted the way they want `msg_1`, `msg_10`, `msg_100`, `msg_11`, `msg_12`, ... if they have 100 items. – Duncan Dec 02 '16 at 15:54
0

All of you thanks, I found the fix for exactly my problem.

string = "msg_{j}"

does not work, no idea why. BUT what works, is that you use the r"". So string = r"msg_{j}" works, for some reason.

J.Horr
  • 117
  • 1
  • 13