[英]How to print a Python dictionary values in a required order?
I have two python dictionary in my code dic_1 and dic_2. 我的代码dic_1和dic_2中有两个python字典。
dic_1 = {'key1': ([1, 2, 3], [4, 5, 'single']),
'key2': ([1, 2, 3], [4, 5, 'single']),
'key3': ([1, 2, 3], [4, 5, 'single'])}
dic_2 = {'key1': ([1, 2, 3], [4, 5, 'married']),
'key2': ([1, 2, 3], [4, 5, 'married']),
'key3': ([1, 2, 3], [4, 5, 'married'])}
for (key, value), (key2, value2) in zip(dic_1.items(), dic_2.items()):
for (one, two, v2one, v2two, ) in zip(value[0], value[1], value2[0], value2[1]):
print(key, one, two)
print(key, v2one, v2two)
and I am getting output like this 我正在得到这样的输出
key1 1 4
key1 1 4
key1 2 5
key1 2 5
key1 3 single
key1 3 married
key2 1 4
key2 1 4
key2 2 5
key2 2 5
key2 3 single
key2 3 married
key3 1 4
key3 1 4
key3 2 5
key3 2 5
key3 3 single
key3 3 married
My output is getting printed like this because of my print statement, but I am looking for output like this 由于我的打印声明,我的输出正在像这样打印,但是我正在寻找这样的输出
key1 1 4
key1 2 5
key1 3 single
key1 1 4
key1 2 5
key1 3 married
key2 1 4
key2 2 5
key2 3 single
key2 1 4
key2 2 5
key2 3 married
key3 1 4
key3 2 5
key3 3 single
key3 1 4
key3 2 5
key3 3 married
How can I achieve this? 我该如何实现? I am not sure where I am making mistake, Thanks 我不确定我在哪里犯错,谢谢
You can just get the keys in on dictionary and then get the corresponding elements with two zips and then print it. 您只需要在字典中输入密钥,然后获取带有两个拉链的相应元素,然后进行打印即可。 I am assuming that all keys in dict1 are in dict2. 我假设dict1中的所有键都在dict2中。
from __future__ import print_function
dic_1 = {'key1': ([1, 2, 3], [4, 5, 'single']),
'key2': ([1, 2, 3], [4, 5, 'single']),
'key3': ([1, 2, 3], [4, 5, 'single'])}
dic_2 = {'key1': ([1, 2, 3], [4, 5, 'married']),
'key2': ([1, 2, 3], [4, 5, 'married']),
'key3': ([1, 2, 3], [4, 5, 'married'])}
for key in sorted(dic_1.keys()):
for one,two in zip(*dic_1[key]):
print(key,one,two)
for one,two in zip(*dic_2[key]):
print(key,one,two)
OUTPUT OUTPUT
key1 1 4
key1 2 5
key1 3 single
key1 1 4
key1 2 5
key1 3 married
key2 1 4
key2 2 5
key2 3 single
key2 1 4
key2 2 5
key2 3 married
key3 1 4
key3 2 5
key3 3 single
key3 1 4
key3 2 5
key3 3 married
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.