简体   繁体   中英

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, ...)?

Dictionaries in Python are not ordered by default. You should use an "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.

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