简体   繁体   English

按顺序打印字典键和值

[英]print dictionary keys and values in ordered manner

I have a dictionary with keys and values as shown below. 我有一本包含键和值的字典,如下所示。

from datetime import datetime
dic = {'pack1':'stage1','pack2':'stage2','pack3':'stage3','pack4':'stage4'}

I want to print the keys and their corresponding values in ordered manner in new line, like 我想按顺序在新行中打印键及其对应的值,例如

Update at 2018-09-18 09:58:03.263575 更新于2018-09-18 09:58:03.263575

**Delivery**           **State** 

'pack1'                 'stage1'

'pack2'                 'stage2'

'pack3'                 'stage3'

'pack4'                 'stage4'

The code I tried is given below 我尝试的代码如下

print("Update at %s\nDelivery\t\t\t\t\t\t\tState \n{}\t\t\t{}".format({key for key in dic.keys()}, {val for val in dic.values()}) %datetime.now())

But it give the output as 但它给出的输出为

Update at 2018-09-18 09:58:03.263575 更新于2018-09-18 09:58:03.263575

**Delivery**                                          **State** 

set(['pack4', 'pack1', 'pack2', 'pack3'])           set(['stage1', 'stage2', 'stage3', 'stage4'])

The values doesn't correspond to their keys, and the output is given in a single line as a set of lists. 这些值与它们的键不对应,并且输出在一行中作为一组列表给出。 How to format the output as my requirement? 如何按照我的要求格式化输出? (There are whitespaces between 'delivery' and State but stack overflow doesn't show them) (“交付”和状态之间存在空格,但堆栈溢出未显示空格)

Dictionary order is not preserved by default. 默认情况下不保留字典顺序。 If you want that for any reason then you need to use OrderedDict instead 如果出于任何原因想要这样做,则需要改用OrderedDict

It is good to note that since Python 3.7, a dict preserves the order in which data is entered. 值得一提的是,自Python 3.7起, dict保留了输入数据的顺序。 Prior to that, you can use an OrderedDict . 在此之前,您可以使用OrderedDict

Although, it seems what you want is to sort the key-value pairs in alphabetical order of keys. 虽然,看来您想要按键的字母顺序对键值对进行排序。 In that case, you can use sorted . 在这种情况下,您可以使用sorted

dic = {'pack1': 'stage1', 'pack2': 'stage2', 'pack3': 'stage3', 'pack4': 'stage4'}

for k, v in sorted(dic.items()):
    print (k + '\t' + v)

Output 输出量

pack1    stage1
pack2    stage2
pack3    stage3
pack4    stage4

From there you can work on the printing format. 从那里您可以处理打印格式。

You need to loop over your input, you can't do this cleanly in a single format and print operation. 您需要循环输入,无法以单一formatprint操作清晰地完成此操作。

If the keys only need to match their values, just do: 如果键只需要匹配它们的值,请执行以下操作:

dic = {'pack1':'stage1','pack2':'stage2','pack3':'stage3','pack4':'stage4'}

for k, v in dic.items():  # .viewitems() on Python 2.7
    print("{}\t\t\t{}".format(k, v))

If you need the output ordered, not just matched up, dict don't provide that guarantee before 3.7 (and don't provide even implementation dependent guarantees until 3.6). 如果您需要排序的输出,而不仅仅是匹配的输出,那么dict在3.7之前不提供该保证(并且直到3.6之前都不提供依赖于实现的保证)。 You'd need a collections.OrderedDict . 您将需要一个collections.OrderedDict You could do a presort though: 你可以做一个预排序:

for k, v in sorted(dic.items()):  # .viewitems() on Python 2.7
    print("{}\t\t\t{}".format(k, v))

so the output ordering is predictable. 因此输出顺序是可预测的。

Can do something like: 可以做类似的事情:

dic = {'pack1':'stage1','pack2':'stage2','pack3':'stage3','pack4':'stage4'}
print('Delivery\t\tState')
for i in dic.items():
   print(('\t'*3).join(i))

Dictionaries are not ordered under python 3.6, so OrderdDict : 字典未在python 3.6下排序,因此OrderdDict

from collections import OrderedDict
dic = OrderedDict([('pack1', 'stage1'), ('pack2', 'stage2'), ('pack3', 'stage3'), ('pack4', 'stage4')])
print('Delivery\t\tState')
for i in dic.items():
   print(('\t'*3).join(i))

All Outputs: 所有输出:

Delivery        State
pack1           stage1
pack2           stage2
pack3           stage3
pack4           stage4

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

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