Example 1: search in dict python
dictionary = { "key1" : 1, "name" : "Jordan", "age" : 21 }
for key in dictionary.keys():
print("the key is {} and the value is {}".format(key, dictionary[key]))
Example 2: get function in dictionary
print('Salary: ', person.get('salary', 0.0))
Example 3: get a value from a dictionary python
dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Never")
Example 4: 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 5: 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')