python - python字典默认值
问题描述
有一个代码 - 它有效。但我不知道在这种情况下是否可以使用“try-except”。
row = [('Normal', 'Deck1', 'user1', 'Deck2', 'Win', '2:0'), ('Normal', 'Deck3', 'user2', 'Deck2', 'Loss', '1:2'), ('Normal', 'Deck3', 'user3', 'Deck1', 'Draw', '2:2')]
table = 'win_loss'
result = ['Win', 'Loss' , 'Draw']
deck = ['Deck1','Deck2','Deck3','Deck4']
def pivot(row):
title, pos = [result, -2] if table == 'win_loss' else [deck, 3]
upd = {}
for i in row:
try:
upd[i[1]]
except KeyError:
upd[i[1]] = {}
try:
upd[i[1]][i[pos]]
except KeyError:
upd[i[1]][i[pos]] = 0
upd[i[1]][i[pos]] += 1
return upd
print(pivot(row))
#{'Deck1': {'Win': 1}, 'Deck3': {'Loss': 1, 'Draw': 1}}
有一个不带“try-except”的选项,但这会在字典的第二级留下空值。而且我不知道如何删除它们了。
def pivot(row):
title, pos = [result, -2] if table == 'win_loss' else [deck, 3]
upd = {fr:{t:0 for t in title} for fr in deck}
for i in row:
upd[i[1]][i[pos]] += 1
#{'Deck1': {'Win': 1, 'Loss': 0, 'Draw': 0}, 'Deck2': {'Win': 0, 'Loss': 0, 'Draw': 0}, 'Deck3': {'Win': 0, 'Loss': 1, 'Draw': 1}, 'Deck4': {'Win': 0, 'Loss': 0, 'Draw': 0}}
copy_upd = upd.copy()
for key in copy_upd:
if sum(copy_upd[key].values()) == 0:
del upd[key]
return upd
#{'Deck1': {'Win': 1, 'Loss': 0, 'Draw': 0}, 'Deck3': {'Win': 0, 'Loss': 1, 'Draw': 1}}
print(pivot(row))
可以删除空值吗?或者如何为不在字典中的键设置默认值?
解决方案
Thanks Woodford for the link Dictionaries and default values
def pivot(row):
from collections import defaultdict
title, pos = [result, -2] if table == 'win_loss' else [deck, 3]
upd = defaultdict(lambda: defaultdict(int))
for i in row:
upd[i[1]][i[pos]] += 1
return upd
#defaultdict(<function pivot.<locals>.<lambda> at 0x7f05740dc940>, {'Deck1': defaultdict(<class 'int'>, {'Win': 1}), 'Deck3': defaultdict(<class 'int'>, {'Loss': 1, 'Draw': 1})})
推荐阅读
- python - 我有一个带有列表的特定列的所有行。从目标列表中选择不包含至少一个元素的行
- java - 如何在不到处指定版本的情况下拥有一个多模块 Maven 项目?
- ajax - 使用 Ajax 在 Django 中将对象文件从视图传递到模板
- python - 如何记忆功能
- python - 在情节图例中写入 $\sqrt(2)$ 而不是 1.414
- r - 在线性拟合中使用矩阵列
- javascript - 选择随机数后如何维护变量
- python - 有人可以解释一下这些在 Pygame 中跳转的代码行吗
- c# - 如何在 C# 中初始化大型静态只读字典?
- python - 如何使用python在windows中获取unix可执行位?