简体   繁体   English

尝试按顺序在python字典中打印多行

[英]Trying to print multiple lines in a python dictionary in order

a = "A"
b = "B"
    board = {
    "1":[a,a,a,a,a,a],
    "2":[a,a,a,a,a,a],
    "3":[a,a,a,a,a,a],
    "4":[b,b,b,b,b,b],
    "5":[b,b,b,b,b,b],
    "6":[b,b,b,b,b,b]
}
for i in board:
    print(board[str(i)],"\n")

I've tried doing this but it doesn't print them in order... I've tried putting a delay on but that doesn't make a difference. 我已经尝试过执行此操作,但是它并没有按顺序打印它们。我已经尝试过延迟一下,但这没有什么区别。

You mean to say that the keys are not accessed in the order in which you inserted them (1, 2, 3, 4, ...)? 您是说不能按插入键的顺序(1、2、3、4,...)访问键?

Dictionaries in Python are not ordered by default. 默认情况下,Python中的字典未排序。 You should use an "OrderedDict" 您应该使用“ OrderedDict”

from collections import OrderedDict
board = OrderedDict([("1", [a,a,a,a,a,a]), ("2", [a,a,a,a,a,a])]) # continued for other keys

for k,v in board.items():
    print k,v

However, like the comments say, if your keys are just numbers it would make more sense to just use a list of lists instead of a dictionary. 但是,就像评论中所说的那样,如果您的键只是数字,那么只使用列表列表而不是字典会更有意义。

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

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