> For the complete documentation index, see [llms.txt](https://lei-d.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lei-d.gitbook.io/leetcode/data-structure/dictionary.md).

# Dictionary

*Mutable, unordered pairs (keys and values) of objects. Keys must be hashable.*&#x20;

*Advantages: O(1) searching for keys. Makes it easy to create trees and other hierarchical data structures. Can be used to create self-documenting code. Many problems can be described in terms of key-value pairs.*&#x20;

*Disadvantages: Only lookup by key. Uses more memory than lists and tuples. Keys must be hashable.*

**Creating**

```python
{'a':1, 'b':2, 'c':3}      # {'a': 1, 'b': 2, 'c': 3}
```

**Creating from other type**

```python
dict(['a',1], ['b',2], ['c',3])      # {'a': 1, 'b': 2, 'c': 3}
dict(('a',1), ('b',2), ('c',3))      # {'a': 1, 'b': 2, 'c': 3}
```

**Retrieving from a key**

```python
# 1st way
d = {'a':1, 'b':2, 'c':3}
d['a']         # 1
d['z']         # raises KeyError

# 2nd way
d = {'a':1, 'b':2, 'c':3}
d.get('a')     # 1
```

**Add a key-value pair**

```python
d = {'a':1, 'b':2, 'c':3}
d['d'] = 100
d              # {'a': 100, 'b': 2, 'c': 3, 'd': 100}
```

**Replacing an existing value**

```python
d = {'a':1, 'b':2, 'c':3}
d['a'] = 100
d              # {'a': 100, 'b': 2, 'c': 3}
```

**Replacing multiple existing values**

```python
d = {'a':1, 'b':2 }
x = {'a':555, 'z':987}
d.update(x, y=10)     # Returns None
d                     # {'a': 555, 'b': 2, 'y': 10, 'z': 987}
```

**Removing an element**

```python
d = {'a':1, 'b':2, 'c':3}
del(d['a'])
d                     # {'c': 3, 'b': 2}
```

**Getting the keys**

```python
d = {'a':1, 'b':2, 'c':3}
d.keys()              # ['a', 'c', 'b'] (Python 2)
d.keys()              # dict_keys(['a', 'b', 'c']) (Python 3)
```

**Getting the values**

```python
d = {'a':1, 'b':2, 'c':3}
d.values()            # [1, 2, 3] (Python 2)
d.values()            # dict_values([1, 2, 3]) (Python 3)
```

**Iterating over the keys**

```python
d = {'a':1, 'b':2, 'c':3}
for k in d:
    print("{0}: {1}".format(k, d[k]))
```

**Iterating over the pairs**

```python
d = {'a':1, 'b':2, 'c':3}
for k, v in d.items()
    print("{0}: {1}".format(k, v)
```

**Iterating over the sorted keys**

```python
d = {'a':1, 'b':2, 'c':3}
for k in sorted(d):
    print("{0}: {1}".format(k, d[k]))
```

**Find the key with max/min value**

```python
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
```

**Check membership**

```python
my_dict = {'x':500, 'y':5874, 'z': 560}
print 'x' in my_dict    # True
```

**Update frequency**

```python
def get_counts(sequence):
    counts = {}
    for x in sequence:
        if x in counts:
            counts[x] += 1
        else:
            counts[x] = 1
    return counts

# a easier way
from collections import defaultdict
def get_counts2(sequence):
    counts = defaultdict(int) # values will initialize to 0
    for x in sequence:
        counts[x] += 1
    return counts
```
