Example 1: python dictionary get default
dictionary = {"message": "Hello, World!"}
data = dictionary.get("message", "")
print(data)
Example 2: python get dictionary keys
newdict = {1:0, 2:0, 3:0}
newdict.keys()
Example 3: python get value from dictionary
dict = {'color': 'blue', 'shape': 'square', 'perimeter':20}
dict.get('shape')
dict.get('volume', 'The key was not found')
Example 4: dict get default
dictionary.get("bogus", default_value)
Example 5: get() python
name_for_userid = {
382: "Alice",
590: "Bob",
951: "Dilbert",
}
def greeting(userid):
return "Hi %s!" % name_for_userid.get(userid, "there")
>>> greeting(382)
"Hi Alice!"
>>> greeting(333333)
"Hi there!"
'''When "get()" is called it checks if the given key exists in the dict.
If it does exist, the value for that key is returned.
If it does not exist then the value of the default argument is returned instead.
'''
Example 6: python dictionary access value by key
datadict = [{'Name': 'John', 'Age': 38, 'City': 'Boston'},
{'Name': 'Sara', 'Age': 47, 'City': 'Charlotte'},
{'Name': 'Peter', 'Age': 63, 'City': 'London'},
{'Name': 'Cecilia', 'Age': 28, 'City': 'Memphis'}]
def getDictVal(listofdic, name, retrieve):
for item in listofdic:
if item.get('Name')==name:
return item.get(retrieve)
getDictVal(datadict, 'Sara', 'City')
df = pd.DataFrame({'Name': ['John', 'Sara','Peter','Cecilia'],
'Age': [38, 47,63,28],
'City':['Boston', 'Charlotte','London','Memphis']})
datadict = df.to_dict('records')