Brackets vs Get function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Brackets vs Get function

Is there a difference in using brackets over the .get function? The output is still the same. Eg: pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs["orange"]) #can be print(pairs.get("orange")) print(pairs.get(7)) print(pairs.get(12345, "not in dictionary"))

18th Jun 2018, 3:27 PM
Sam Kim
Sam Kim - avatar
1 Answer
+ 1
get return none when element is not found in dictionary while brackets will raise keyerror if element is not present into dictionary. Run below code to make it clear. pairs = {1: "apple", 'orange': [2, 3, 4], True: False, None: "True", } print(pairs['orange']) print(pairs.get('orange')) print(pairs.get(7)) print(pairs['saga'])
18th Jun 2018, 4:01 PM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar