Reputation: 3843
In my textbook I read that a newbie needs some time to recognize this construction:
choice = 'ham'
print ({
'spam': 1.25,
'ham': 1.99,
'eggs': 0.99,
'bacon': 1.10
}[choice])
With the result:
The result is 1.99
To tell the truth, I can't even grasp a tail of the knot to tell nothing of untying it. Could you clarify it to me a bit?
Upvotes: 2
Views: 224
Reputation: 544
You might even stick a .get in there to return a value if the choice isn't in the dictionary.
mapping = {'spam': 1.25, 'ham': 1.99, 'eggs': 0.99, 'bacon': 1.10}
choice = 'beans'
price = mapping.get(choice, 'not listed')
print(price)
will return
not listed
Upvotes: 3
Reputation: 1121486
It's a python dictionary literal, combined with a lookup using choice
as a key:
mapping = {'spam': 1.25, 'ham': 1.99, 'eggs': 0.99, 'bacon': 1.10}
choice = 'ham'
price = mapping[choice]
print(price)
Upvotes: 5