+ 2

Get method with a None argument in Python

Hi Community I have two (2) questions in regards to the piece of Python codes below: for code in portfolio_list: res = EXCHANGE_DATA.get(code, None) if res: print('{:<6} {:<20} {:>8.2f}'.format(code, *res) Question 1) What does the if do? Is it just to ensure it's executed to every line in the portfolio_list? Question 2) I understand that the "None" argument in the get method is to bypass a KeyError is a value is not found, but what does it return? Is it a "blank" or does it return the last found value? Thanks for your help!

8th Sep 2019, 1:37 AM
Jin
Jin - avatar
2 ответов
+ 3
Q2. The second argument of dict.get(key,default=None) is returned in case "key" doesn't exist. In this case, None is returned if the key isn't found. Q1. The block under the if statement is only executed if the key was found on the dictionary (because something truthy other than None was returned). if None: print(4) else: print(2) # 2
8th Sep 2019, 4:50 AM
Diego
Diego - avatar