简体   繁体   中英

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

**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

**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

It is good to note that since Python 3.7, a dict preserves the order in which data is entered. Prior to that, you can use an 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 .

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.

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). You'd need a 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 :

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

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