0

There is a code - it works. But I don't know if 'try-except' can be used in this case.

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}}

There is an option without 'try-except', but this leaves null values at the second level of the dictionary. And I don't know how to remove them anymore.

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))

Can null values be removed? Or how to set a default value for a key that is not in the dictionary?

1 Answers1

0

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})})