Python dictionaries - cheatsheet
Definition
Define dictionary (pairs key-value)
1
2
3
4alien_0 = {
'color': 'green',
'points': 2
}Define empty dictionary
1
alien_0 = {}
Define ordered dictionary (keep order in which the data was entered)
1
2
3
4
5from collections import OrderedDict
fav_languages = OrderedDict()
fav_languages['angeles'] = ['java', 'python']
fav_languages['juan'] = ['php', 'java']Get item
1
2alien_color = alien_0.get('color')
alien_points = alien_0.get('points', 0)Get lenth
1
num_alien_traits = len(alien0)
Basic modifications
Add
1
alien_0['speed'] = 1.5
Modify
1
2
3
4
5alien_0 = {
'color': 'green',
'points': 2
}
alien_0['color'] = 'purple'Remove
1
del alien_0['points']
Iteration
Loop through items
1
2for key, value in alien0.items():
print(key + ": " + value)Loop through keys
1
2
3
4
5for key in alien0.keys():
print("key: " + key)
for key in sorted(alien0.keys()):
print("key: " + key)Loop through values
1
2for value in alien0.values():
print("value: " + value)