gpt4 book ai didi

python - 重新排列字典的输出 (Python)

转载 作者:行者123 更新时间:2023-12-01 05:32:25 27 4
gpt4 key购买 nike

我有以下代码:

dic = {'key1': [0, 0, 0], 'key2': [1, 1, 1], 'key3': [2, 2, 2]}

keys = dic.keys()
values = dic.values()

for i in range(0, len(keys)):
print keys[i]
for j in range(0, len(values)):
print values[i][j]

它产生的输出如下:

key3
2
2
2
key2
1
1
1
key1
0
0
0

我想要的是以下输出:

key3 key2 key1
2 1 0
2 1 0
2 1 0

非常感谢!

最佳答案

假设所有值列表都具有相同的长度,并且 keys 具有您想要的 header 顺序,则应该这样做:

print '\t'.join(keys)
for row in zip(*[dic[k] for k in keys]):
print '\t'.join(map(str, row))

更新

我使用列表理解来保证排序,但根据Python documentation 、 dict.keys() 和 dict.values() 如果字典之间没有更改,则保证顺序。考虑到这一点,可以删除上面的列表理解,并且代码可以简单如下:

print '\t'.join(keys)
for row in zip(*values):
print '\t'.join(map(str, row))

关于python - 重新排列字典的输出 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19910270/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com