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': 'Zara', 'Age': 7, 'Class': 'First'}
4dict['Age'] = 8; # update existing entry
5dict['School'] = "DPS School"; # Add new entry
6
7print "dict['Age']: ", dict['Age']
8print "dict['School']: ", dict['School']
9
1# Create a list of dictionary
2datadict = [{'Name': 'John', 'Age': 38, 'City': 'Boston'},
3 {'Name': 'Sara', 'Age': 47, 'City': 'Charlotte'},
4 {'Name': 'Peter', 'Age': 63, 'City': 'London'},
5 {'Name': 'Cecilia', 'Age': 28, 'City': 'Memphis'}]
6
7# Build a function to access to list of dictionary
8def getDictVal(listofdic, name, retrieve):
9 for item in listofdic:
10 if item.get('Name')==name:
11 return item.get(retrieve)
12
13 # Use the 'getDictVal' to read the data item
14getDictVal(datadict, 'Sara', 'City') # Return 'Charlotte'
15
16# -------------------
17# to convert a dataframe to data dictionary
18df = pd.DataFrame({'Name': ['John', 'Sara','Peter','Cecilia'],
19 'Age': [38, 47,63,28],
20 'City':['Boston', 'Charlotte','London','Memphis']})
21
22datadict = df.to_dict('records')
23
1# Get a value from a dictionary in python from a key
2
3# Create dictionary
4dictionary = {1:"Bob", 2:"Alice", 3:"Jack"}
5
6# Retrieve value from key 2
7entry = dictionary[2]
8
9# >>> entry
10# Alice