Dictionaries
Dictionaries in Python
# Define dict:
dict = {
'k1': 'some data',
7: ['can', 'be', 'a', 'list']
}
# Dictionaries are not position oriented, they are key oriented
# To get the data:
dict['k1'] # prints 'some data'
print(dict[7]) # prints ['can', 'be', 'a', 'list']
Dictionaries are mutable and can be changed
dict[7] = 'new value'
You cannot sort dictionaries, you should use keys to get the data
people_weight_dict = {
'john': 123,
'mike': 170,
'robert': 167
}
# To change john's weight you would do
people_weight_dict['john'] = 134
You can pop items from dictionaries
people_weight_dict.pop('mike')
Syntax:
dict.pop('key')
Clear method
people_weight_dict.clear()
# It will still be a dictionary but it will be an empty one
Adding items to dictionary:
people_weight_dict = {
'john': 123,
'mike': 170,
'robert': 167
}
# Adding the data
people_weight_dict['new_key'] = 'new data to be added'
# At this point the dict has been permanently modified and adjusted with a new entry
Accessing item from a list in the dict
people_weight_dict = {
'john': 123,
'mike': 170,
'robert': 167,
'items': ['apple', 'banana', 'orange']
}
print(people_weight_dict['items'][2]) # prints orange
Accessing items from a dictionary in a list in a dict
people_weight_dict = {
'john': 123,
'mike': 170,
'robert': 167,
'items': ['apple', 'banana', {'k1': 'some value'}]
}
print(people_weight_dict['items'][2]['k1']) # prints 'some value'
Remove items for dictionary:
people_weight_dict = {
'john': 123,
'mike': 170,
'robert': 167,
'items': ['apple', 'banana', {'k1': 'some value'}]
}
people_weight_dict.pop['items']
print(people_weight_dict)
# It will print:
people_weight_dict = {
'john': 123,
'mike': 170,
'robert': 167
}
Last updated