1#Creating dictionaries
2dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
3dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
4
5#Creating new pairs and updating old ones
6dict1['area'] = 25 #{'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
7dict2['perimeter'] = 20 #{'color': 'red', 'edges': 4, 'perimeter': 20}
8
9#Accessing values through keys
10print(dict1['shape'])
11
12#You can also use get, which doesn't cause an exception when the key is not found
13dict1.get('false_key') #returns None
14dict1.get('false_key', "key not found") #returns the custom message that you wrote
15
16#Deleting pairs
17dict1.pop('volume')
18
19#Merging two dictionaries
20dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
21dict1 #{'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}
22
23#Getting only the values, keys or both (can be used in loops)
24dict1.values() #dict_values(['red', 'square', 25, 4, 20])
25dict1.keys() #dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
26dict1.items()
27#dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])
1d = {'key': 'value'}
2print(d)
3# {'key': 'value'}
4d['mynewkey'] = 'mynewvalue'
5print(d)
6# {'key': 'value', 'mynewkey': 'mynewvalue'}
7
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
1dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
2print(dict['Name']) # Zara
3print(dict['Age']) # 7
4