How to lookup from and insert into a HashMap efficiently?

The entry API is designed for this. In manual form, it might look like let values = match map.entry(key) { Entry::Occupied(o) => o.into_mut(), Entry::Vacant(v) => v.insert(default), }; One can use the briefer form via Entry::or_insert_with: let values = map.entry(key).or_insert_with(|| default); If default is already computed, or if it’s OK/cheap to compute even when it isn’t … Read more

How can I add new keys to a dictionary?

You create a new key/value pair on a dictionary by assigning a value to that key d = {‘key’: ‘value’} print(d) # {‘key’: ‘value’} d[‘mynewkey’] = ‘mynewvalue’ print(d) # {‘key’: ‘value’, ‘mynewkey’: ‘mynewvalue’} If the key doesn’t exist, it’s added and points to that value. If it exists, the current value it points to is … Read more