Astudent
Astudent

Reputation: 196

Print dictionary values linked to keys which are in a list

So let's say I have a list of words:

listA = ['apple', 'bee', 'croissant']

and a dictionary:

dictA = {'bee': '100', 'apple': '200', 'croissant': '450'}

How do I get a print like this?

apple costs 200
bee costs 100
croissant costs 450

The problem here is the alphabetical order, it is the reason I need to get the values from the dictionary using the list. I hope the question is understandable.

Upvotes: 2

Views: 142

Answers (1)

Sufiyan Ghori
Sufiyan Ghori

Reputation: 18763

You don't need a list for ordering your dict, you can just use sorted to sort by key,

dictA = {'bee': '100', 'apple': '200', 'croissant': '450'}

for key in sorted(dictA):
    print ("{} costs {}".format(key, dictA[key]))

# output,

apple costs 200
bee costs 100
croissant costs 450

or one liner,

print (sorted("{} costs {}".format(key, dictA[key]) for key in dictA))

#  output,
['apple costs 200', 'bee costs 100', 'croissant costs 450']

Upvotes: 1

Related Questions