Example 1: python dictionary
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
dict1['area'] = 25
dict2['perimeter'] = 20
print(dict1['shape'])
dict1.get('false_key')
dict1.get('false_key', "key not found")
dict1.pop('volume')
dict1.update(dict2)
dict1
dict1.values()
dict1.keys()
dict1.items()
Example 2: python dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Example 3: for key value in dict python
a_dict = {"color": "blue", "fruit": "apple", "pet": "dog"}
for key in a_dict:
print(key, '->', a_dict[key])
Example 4: 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 5: python dict access
my_dict = {'name':'Jack', 'age': 26}
my_dict['name']
Example 6: how to get element from dictionary python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8;
dict['School'] = "DPS School";
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']