简体   繁体   English

Python中带for循环和dict的字符串控制

[英]String control with for-loop and dict in Python

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 . 这将引发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). 我测试了所有功能,一切正常,直到我了解了循环部分(如果我使用print()而不是循环,则可以正常工作)。

You'd want to iterate over your dictionary. 您想遍历字典。

For Python 2.x: 对于Python 2.x:

for key, value in msgs.iteritems():

For Python 3.x: 对于Python 3.x:

for key, value in msgs.items():

More details can be found here . 可以在此处找到更多详细信息。

In your case, replace len(msgs) - 1 with len(msgs) + 1 , 在您的情况下,将len(msgs) - 1替换为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

I think your are missing the .keys() method of dict object. 我认为您缺少dict对象的.keys()方法。 It returns a list of all keys in the dict object. 它返回dict对象中所有键的列表。

for key in msgs.keys():
    print msgs[key]

Check out the solution from SarTheFirst. 从SarTheFirst查看解决方案。 If you want to print in sorted order: 如果要按排序顺序打印:

for key in sorted(msg):
    print(msgs[key])

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"" . 但是有效的是您使用了r"" So string = r"msg_{j}" works, for some reason. 因此出于某种原因, string = r"msg_{j}"可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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