1dictionary = {"message": "Hello, World!"}
2
3data = dictionary.get("message", "")
4
5print(data) # Hello, World!
6
1dict = {'color': 'blue', 'shape': 'square', 'perimeter':20}
2dict.get('shape') #returns square
3
4#You can also set a return value in case key doesn't exist (default is None)
5dict.get('volume', 'The key was not found') #returns 'The key was not found'
1my_dict = {'a': 1, 'b': 2, 'c': 3}
2# keys = list(item.keys())
3# the upper commented code give the list of the keys.
4keys = ['a', 'b', 'c', 'd'] # if some body give the list of the keys that wasn't match with my_dict
5
6for key in keys:
7 print(my_dict.get(key, 'default value when key not exist'))
8
9"""output:
101
112
123
13default value when key not exist
14"""
1#!/usr/bin/python
2
3dict = {'Name': 'Zabra', 'Age': 7}
4print "Value : %s" % dict.get('Age')
5print "Value : %s" % dict.get('Education', "Never")
1# The get() method on dicts
2# and its "default" argument
3
4name_for_userid = {
5 382: "Alice",
6 590: "Bob",
7 951: "Dilbert",
8}
9
10def greeting(userid):
11 return "Hi %s!" % name_for_userid.get(userid, "there")
12
13>>> greeting(382)
14"Hi Alice!"
15
16>>> greeting(333333)
17"Hi there!"
18
19'''When "get()" is called it checks if the given key exists in the dict.
20
21If it does exist, the value for that key is returned.
22
23If it does not exist then the value of the default argument is returned instead.
24'''
25# transferred by @ebdeuslave
26# From Dan Bader - realpython.com