Python Application Notes: dict

Collect common operations in dict, including nested dictionaries, iteration, sorting.

1. Basic operations

Basic operations of dict are as follows, excerpt from Python documentation here.

len(d)               # Return the number of items
d[key]               # Return the item of d with key key
d[key] = value       # Set d[key] to value.
del d[key]           # Remove d[key] from d. Raises a KeyError if key is not in the map.
key in d             # Return True if d has a key key, else False.
key not in d         # Equivalent to not key in d.
iter(d)              # Return an iterator over the keys of the dictionary
clear()              # Remove all items from the dictionary.
copy()               # Return a shallow copy of the dictionary.
get(key[, default])  # Return the value for key if key is in the dictionary
items()              # Return a new view of the dictionary’s items ((key, value) pairs)
keys()               # Return a new view of the dictionary’s keys.
pop(key[, default])  # If key is in the dictionary, remove it and return its value
popitem()            # Remove and return an arbitrary (key, value) pair from the dictionary.
update([other])      # Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update()             # accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
values()             # Return a new view of the dictionary’s values. setdefault(key[, default])  If key is in the dictionary, return its value. 

classmethod fromkeys(seq[, value])    # Create a new dictionary with keys from seq and values set to value.

1.1 Dict comprehensions

Create a dictionary using Dict Comprehensions. It is quite useful to replace keys or values of a dictionary according to a predefined pattern. For instance, all float values are rounded to two decimal points.

node_labels = {k : round(v, 2) for k, v in node_labels.items()}

1.2 Change keys or values

# change the key
d[new_key] = d.pop(old_key) # d[old_key] will be deleted. Note that it will raise `KeyError` if `d[old_key]` is undefined

# change the value
d[key] = new_value

2. Nested dictionaries

Implement the perl’s autovivification feature [1-2]> by:

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value​

​# an example
a = AutoVivification()
a[1][2][3] = 4
a[1][3][3] = 5
a[1][2]['test'] = 6

>>> print(a)
{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}

Here is the detailed explanation of the above code. A paragraph excerpt from Wikipedia: Autovivification:

In the Perl programming language, autovivification is the automatic creation of new arrays and hashes as required every time an undefined value is dereferenced. Perl autovivification allows a programmer to refer to a structured variable, and arbitrary sub-elements of that structured variable, without expressly declaring the existence of the variable and its complete structure beforehand.

3. Iteration

d = dict()

# iterate over keys
for key in d.keys:

# iterate over values
for value in d.values()

# iterate over key and value
for key, value in d.items():  # a list of tuples <key , value>

4. Sort

Use the build-in function Sorted to sort and save its results into an OrderedDict (remember the order that items were inserted):

from collections import OrderedDict 

# usage
sorted(iterable[, key][, reverse]) # Return a new sorted list from the items in iterable.

# regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

# dictionary sorted by key
>>> OrderedDict(sorted(d.items())) # OR OrderedDict(sorted(d.items(), key=lambda x: x[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

# dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda x: x[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

# dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda x: len(x[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

[1]StackOverflow: What is the best way to implement nested dictionaries in Python?
[2]StackOverflow: In python, how does the following AutoVivification class work?



Leave a Reply

Your email address will not be published. Required fields are marked *