python字典默认值

时间:2021-05-04 17:46:17

标签: python dictionary default default-value

有一个代码 - 它有效。但我不知道在这种情况下是否可以使用 '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))

可以删除空值吗?或者如何为字典中没有的键设置默认值?

1 个答案:

答案 0 :(得分:0)

感谢 Woodford 提供链接 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})})