Example 1: python get dict values as list
food_list=list(data.values())
print(food_list)
Example 2: python get value from dictionary
dict = {'color': 'blue', 'shape': 'square', 'perimeter':20}
dict.get('shape') #returns square
#You can also set a return value in case key doesn't exist (default is None)
dict.get('volume', 'The key was not found') #returns 'The key was not found'
Example 3: dict get list of values
list(d.values())
Example 4: get a value from a dictionary python
#!/usr/bin/python
dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Never")
Example 5: python dictionary access value by key
# Create a list of dictionary
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'}]
# Build a function to access to list of dictionary
def getDictVal(listofdic, name, retrieve):
for item in listofdic:
if item.get('Name')==name:
return item.get(retrieve)
# Use the 'getDictVal' to read the data item
getDictVal(datadict, 'Sara', 'City') # Return 'Charlotte'
# -------------------
# to convert a dataframe to data dictionary
df = pd.DataFrame({'Name': ['John', 'Sara','Peter','Cecilia'],
'Age': [38, 47,63,28],
'City':['Boston', 'Charlotte','London','Memphis']})
datadict = df.to_dict('records')
Example 6: 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 a good format:
for i in dictionary:
print(i, ":")
for j in dictionary[i]:
print(" ", j, ":", dictionary[i][j])
print()
# Output:
Jeff :
lastname : bobson
age : 55
working : True
James :
lastname : Bobson
age : 34
working : False
# For just a quick reading:
for k, v in dictionary.items():
print(k, v)
# Output:
Jeff {'lastname': 'bobson', 'age': 55, 'working': True}
James {'lastname': 'Bobson', 'age': 34, 'working': False}