简体   繁体   中英

How to use a dictionary to print its partner value

Not sure if the title is specific enough.

words = ['sense', 'The', 'makes', 'sentence', 'perfect', 'sense', 'now']
numbers = ['1', '2', '3', '4', '5', '6']
dictionary = dict(zip(numbers, words))
print(dictionary)
correctorder = ['2', '4', '7', '3', '5', '6']

I'm simply trying to figure out how exactly I can print specific values from the dictionary using the correctorder array so that the sentence makes sense.

You can just iterate over correctorder and get the corresponding dict value, then join the result together.

' '.join(dictionary[ele] for ele in correctorder)

This is assuming that you fix numbers to include '7' at the end.

>>> ' '.join(dictionary[ele] for ele in correctorder)
'The sentence now makes perfect sense'

What you want is this.

for i in correctorder: 
    print dictionary[i]," ",

Short and simple. As Mitch said, fix the 7 though.

You could use operator.itemgetter to avoid an explicit loop:

>>> from operator import itemgetter
>>> print(itemgetter(*correctorder)(dictionary))

To concatenate this simply use str.join :

>>> ' '.join(itemgetter(*correctorder)(dictionary))

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