Example 1: 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')
Example 2: how to print a value from a dictionary in python
dictionary={
"Jeff":{
"lastname":"bobson",
"age":55,
"working":True
},
"James":{
"lastname":"Bobson",
"age":34,
"working":False
}
}
for i in dictionary:
print(i, ":")
for j in dictionary[i]:
print(" ", j, ":", dictionary[i][j])
print()
Jeff :
lastname : bobson
age : 55
working : True
James :
lastname : Bobson
age : 34
working : False
for k, v in dictionary.items():
print(k, v)
Jeff {'lastname': 'bobson', 'age': 55, 'working': True}
James {'lastname': 'Bobson', 'age': 34, 'working': False}
Example 3: python dictionary get value
dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Never")