DictionariesΒΆ

From PairsΒΆ

colors = ["red", "green", "blue"]
d = dict(enumerate(colors))

colors = ["red", "green", "blue"]
d = {}
for i, color in enumerate(colors):
    d[i] = color
# Good
colors = ["red", "green", "blue"]
d = dict(enumerate(colors))

# Bad
colors = ["red", "green", "blue"]
d = {}
for i, color in enumerate(colors):
    d[i] = color

πŸ’‘ learnt from:

CountΒΆ

from collections import Counter

colors = ["green", "blue", "red", "green", "red", "red"]

counts = Counter(colors)

from collections import defaultdict

colors = ["green", "blue", "red", "green", "red", "red"]

d = defaultdict(int)
for color in colors:
    d[color] += 1
# Good
from collections import Counter

colors = ["green", "blue", "red", "green", "red", "red"]

counts = Counter(colors)

# Bad
from collections import defaultdict

colors = ["green", "blue", "red", "green", "red", "red"]

d = defaultdict(int)
for color in colors:
    d[color] += 1

LayeringΒΆ

from collections import ChainMap

cli_args = {"user": "FooBar", "cmd": "ls -all"}
env_args = {"user": "Johndoe"}
cfg_args = {"user": "default", "cwd": "/home/default", "cmd": "ls"}

config = ChainMap(cli_args, env_args, cfg_args)

cli_args = {"user": "FooBar", "cmd": "ls -all"}
env_args = {"user": "Johndoe"}
cfg_args = {"user": "default", "cwd": "/home/default", "cmd": "ls"}

config = {}
config.update(cfg_args)
config.update(env_args)
config.update(cli_args)
# Good
from collections import ChainMap

cli_args = {"user": "FooBar", "cmd": "ls -all"}
env_args = {"user": "Johndoe"}
cfg_args = {"user": "default", "cwd": "/home/default", "cmd": "ls"}

config = ChainMap(cli_args, env_args, cfg_args)

# Bad
cli_args = {"user": "FooBar", "cmd": "ls -all"}
env_args = {"user": "Johndoe"}
cfg_args = {"user": "default", "cwd": "/home/default", "cmd": "ls"}

config = {}
config.update(cfg_args)
config.update(env_args)
config.update(cli_args)

πŸ’‘ learnt from: