Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在两个不同的列中打印词典_Python_Python 3.x_Dictionary_Formatting - Fatal编程技术网

Python 在两个不同的列中打印词典

Python 在两个不同的列中打印词典,python,python-3.x,dictionary,formatting,Python,Python 3.x,Dictionary,Formatting,我有一本这种格式的词典: my_dict = {'a':{'x':10}, 'b':{'z':7}, 'w':{'y':4}, 'y':{'q':1}, 'q':{'m':15}, 't':{'z':34}, 's':{'y':44}} 每个字符串映射到一个{string:value}的字典。我想打印第一个字符串和字典中的字符串。 我希望它分为两列,如下所示: a:x | b:z w:y | y:q q:m | t:z s:y | 我该怎么做 for key, value in my_dic

我有一本这种格式的词典:

my_dict = {'a':{'x':10}, 'b':{'z':7}, 'w':{'y':4}, 'y':{'q':1}, 'q':{'m':15}, 't':{'z':34}, 's':{'y':44}}
每个字符串映射到一个
{string:value}
的字典。我想打印第一个字符串和字典中的字符串。 我希望它分为两列,如下所示:

a:x | b:z
w:y | y:q
q:m | t:z
s:y |
我该怎么做

for key, value in my_dict.items():
    print('{}:{}'.format(key, value.key?))

这应该能奏效。它不能准确地打印出您想要的内容,因为内置的
dict
s是散列的,因此是无序的。下面的
chunk
函数将列表平均分割为
n
大小的块。因此,您需要使用
my_dict.items()
在字典中进行迭代,并使用
my_dict.items()中的每个元素创建对

在设置了对之后,您所要做的就是对
对中的元素进行适当的索引。
列表(x[0][1].keys())[0]
语法只是从嵌套字典中获取键,并假设嵌套字典仅包含一个键

for x in pairs:
    if len(x) > 1:
        print("{}: {} | {}: {}".format(x[0][0], list(x[0][1].keys())[0], x[1][0], list(x[1][1].keys())[0]))
    else:
        print("{}: {}".format(x[0][0], list(x[0][1].keys())[0]))
它打印了这个:

b: z | s: y
w: y | y: q
q: m | t: z
a: x
编辑:根据下面的评论,是的,有一种按字母顺序打印的方法。只需在
list(my_dict.items())
返回的列表上使用
sorted
,即可按每个元组中的第一个元素进行排序

res = sorted(list(my_dict.items()), key = lambda x: x[0])

# new chunks based on sorted list
pairs = chunks(res, 2)
成对
看起来像这样(它实际上是一个发电机,但在引擎盖下是这样的):


从那里,你可以对上面的循环使用相同的

为什么“a”映射到“b”,而“w”映射到“u”,而“q”映射到“m”?然后“t”继续前面的模式,映射到“s”。。。这里的逻辑似乎不正确。
{'x',10}
..列表或元组到底是什么?您的字典包含作为值的集合。但是集合的第一项是不确定的(因为它们在设计上是无序的)。你是说绳子吗?你能澄清一下吗?哎呀!我的意思是
不是为了澄清,有没有办法按字母顺序得到它?
res = sorted(list(my_dict.items()), key = lambda x: x[0])

# new chunks based on sorted list
pairs = chunks(res, 2)
[[('a', {'x': 10}), ('b', {'z': 7})], [('q', {'m': 15}), ('s', {'y': 44})], [('t', {'z': 34}), ('w', {'y': 4})], [('y', {'q': 1})]]