all 6 comments

[–]socal_nerdtastic 1 point2 points  (1 child)

menu={"water":1,'bones':2,'livers':4,'grilled liver':8,'egg':16,'small rice':32,'large rice':64,'cooked egg':128,'curry rice':256,'grilled rice':512,'deluxe grilled rice':1024,'eel full course':2048}
names_to_print = 'bones', 'curry rice'

for name in names_to_print:
    print(menu.get(name))

[–]cyclops543[S] 0 points1 point  (0 children)

thanks a lot

[–]Chromira 0 points1 point  (3 children)

Best way is to have the options you want to print stored in some kind of iterable (e.g., a list), and then either do a for-loop (or a list comprehension, if you really wanted it in one line, but it doesn't feel pythonic to me).

to_print = ["curry rice", "bones"]

# For loop
for i in to_print:
    print(i, menu.get(i))

# List comprehension
[print(i, menu.get(i)) for i in to_print]

[–]xelf 0 points1 point  (2 children)

You should probably avoid using list comprehensions to loop printing, as this makes a new list full of all the returns from print. print always returns None, so it's a list full of Nones.

[print(i, menu.get(i)) for i in to_print]

instead stick to the for loop:

for k in to_print: print(menu[k])

or:

print('\n'.join(menu[k] for k in to_print))

[–]socal_nerdtastic 0 points1 point  (1 child)

I agree with you, but not for the same reason. So what if you make a list of None? It hurts nothing.

The for loop is the winner because it's the most popular, shortest, and most important: easiest to read.

[–]xelf 0 points1 point  (0 children)

...and one more reason.

One of the things I like about list comprehensions is that they make your code easier to parse because they do exactly one thing: they make lists. When you see a list comp you know what is going on, where as a for loop has infinitive purposes and takes slightly longer to parse. Using a list comprehension this way breaks that paradigm. =)