https://github.com/lguyogiro/betterdict
How Python dicts should behave
https://github.com/lguyogiro/betterdict
data-structures dict python
Last synced: 3 months ago
JSON representation
How Python dicts should behave
- Host: GitHub
- URL: https://github.com/lguyogiro/betterdict
- Owner: Lguyogiro
- License: mit
- Created: 2016-12-09T00:16:45.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2018-05-02T17:53:22.000Z (over 7 years ago)
- Last Synced: 2025-04-05T23:51:09.603Z (6 months ago)
- Topics: data-structures, dict, python
- Language: Python
- Size: 16.6 KB
- Stars: 5
- Watchers: 1
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# BetterDicts
Mergeable Python dictionary/OrderedDict/defaultdict/Counter with arithmetic
operator support.## Setup
```python
pip install betterdicts
```## Examples
Use operator to add, substract, multipy or divide values with like keys.
```python
from betterdicts import BetterDict
>>> hour1_views = BetterDict({"user1": 4, "user2": 5, "user3": 1})
>>> hour2_views = BetterDict({"user4": 9, "user2": 2, "user6": 6})
>>> hour1_views + hour2_views
{'user1': 4, 'user2': 7, 'user3': 1, 'user4': 9, 'user6': 6}
```Merge dictionaries with custom logic:
```python
from betterdicts import BetterDict, merged
# in-place
>>> en = BetterDict({1: "one", 2: "two", 3: "three"})
>>> es = BetterDict({1: "uno", 2: "dos", 3: "tres"})
>>> en.merge(es, lambda a, b: [a,b])
>>> en
{1: ['one', 'uno'], 2: ['two', 'dos'], 3: ['three', 'tres']}# or return a new, merged BetterDict:
>>> en = BetterDict({1: "one", 2: "two", 3: "three"})
>>> es = BetterDict({1: "uno", 2: "dos", 3: "tres"})
>>> merged(en, es, lambda a, b: [a, b])
{1: ['one', 'uno'], 2: ['two', 'dos'], 3: ['three', 'tres']}
```You can also perform arithmetic with BetterDicts and scalars:
```python
>>> raw_counts = BetterDict({'the': 1432, 'she': 600, 'wookie': 25})
>>> total = 10000.
>>> relative_freqs = raw_counts / total
>>> relative_freqs
{'she': 0.06, 'the': 0.1432, 'wookie': 0.0025}
>>> relative_freqs * 100
{'she': 6.0, 'the': 14.32, 'wookie': 0.25}
```