collections.OrderedDict is ideal if key order is important for your goal.
import collections
tasks = collections.OrderedDict(laundry=0.5, shopping=2, clean=2)
tasks['movie'] = 2
tasks
tasks.keys
# OrderedDict([('laundry', 0.5), ('shopping', 2), ('clean', 2), ('movie', 2)])
# odict_keys(['laundry', 'shopping', 'clean', 'movie'])
Can be initialized with a function that takes no arguments and provides the default value if a requested key cannot be found.
from collections import defaultdict
classes = defaultdict(lambda: 'Outside')
classes['Math'] = 'B23'
classes['Physics'] = 'D24'
classes['Math']
#Outcome: B23. Defaultfict behaves just like a standard dictionary, except it allows the value of a non-existent key to return.
classes['English']
# Outside.
Behaves like its name. The data structure allows you to group multiple dictionaries together like a chain.
The default value that we specified is returned when the non-existence key is provided. Now you don’t need to take the time to map 20 classes that are taught outside to Outside values.
You want to take note of the lists of your friends and their information. Each friend’s information will be represented as a dictionary with name and age.
Once you have the information on all of your friends, you contemplate how to put all that information together into a single place. You discover ChainMap.
from collections import ChainMap
#Create multiple dictionaries of friends and their information
friend1 = {'name':'Ben','age':23}
friend2 = {'name':'Thinh', 'age': 25}
#Group these dictionaries together
friends = ChainMap(friend1, friend2)
friends
# ChainMap({'name': 'Ben', 'age': 23}, {'name': 'Thinh', 'age': 25})
So how does the dictionary search for a provided key? It will search for the key from left to right and return the value once the key is found.
friends['name']
Outcome: Ben
provides a read-only view into the wrapped dictionary’s data. This discourages users from editing the dictionary.
Create a Read-Only Dictionary
Scenario:
As you know, the dictionary allows the users to access and change the items within the dictionary.
What if you just want to use the dictionary to provide the users with information about the key without changing it? For example, creating a map of classes that could not be changed by students. Then you should consider usingMappingProxyType .
from types import MappingProxyType
#Can read and edit
classes = {'Math': 'B23','Physics':'D24'}
classes['Math']
classes["Math"] = 'B21'
#Can read
classes['Math']
#But can no longer edit
classes["Math"] = "D15"
Outcome:
TypeError: 'mappingproxy' object does not support item assignment
As you can see, now the students can no longer change the room to confuse their classmates.
TODO:
Lists to Dict:
https://thispointer.com/python-how-to-convert-a-list-to-dictionary/