Is this code for making a nested dictionary correct?

感情迁移 提交于 2020-12-13 03:09:25

问题


I had some problems with the code that was given in an answer at this post: Can I use a nested for loop for an if-else statement with multiple conditions in python?

import pprint

board = {
    '1a': 'bking',
    '4e': 'bpawn',
    '2c': 'bpawn',
    '3f': 'bpawn',
    '5h': 'bbishop',
    '6d': 'wking',
    '7f': 'wrook',
    '2b': 'wqueen'
}

count = {}
for k, v in board.items():
    count[k[0]][k[1:]] = v
pprint.pprint(count)

I wanted to get the following dictionary:

count = {'b': {'king': 1, 'pawn': 3, 'bishop': 1},
         'w': {'king': 1, 'rook': 1, 'queen': 1}}

Received error:

Traceback (most recent call last):
  File "/Users/Andrea_5K/Library/Mobile Documents/com~apple~CloudDocs/automateStuff2/ch5/flatToNest2.py", line 21, in <module>
    count[k[0]][k[1:]] = v
KeyError: '1'

回答1:


OP comment says output should be the count of each piece. That can be done as follows using setdefault

nested = {}
for k, v in board.items():
    nested.setdefault(v[0], {})  # default dictionary for missing key
    nested[v[0]][v[1:]] = nested[v[0]].get(v[1:], 0) + 1 # increment piece count

pprint.pprint(nested)
# Result
{'b': {'bishop': 1, 'king': 1, 'pawn': 3},
 'w': {'king': 1, 'queen': 1, 'rook': 1}}



回答2:


The problem in your code is that when you access nested[k[0]], you expect nested to already have this key, and you expect the corresponding value to be a dict.

The easiest way to solve this problem is to use a defaultdict(dict) that will create it on the fly when needed:

from collections import defaultdict

board = {
    '1a': 'bking',
    '4e': 'bpawn',
    '2c': 'bpawn',
    '3f': 'bpawn',
    '5h': 'bbishop',
    '6d': 'wking',
    '7f': 'wrook',
    '2b': 'wqueen'
}

nested = defaultdict(dict)
for k, v in board.items():
    nested[k[0]][k[1:]] = v
print(nested)

# defaultdict(<class 'dict'>, {'1': {'a': 'bking'}, '4': {'e': 'bpawn'}, '2': {'c': 'bpawn', 'b': 'wqueen'}, '3': {'f': 'bpawn'}, '5': {'h': 'bbishop'}, '6': {'d': 'wking'}, '7': {'f': 'wrook'}})



回答3:


If all you need is counts, use collections.Counter, and split the result using a collections.defaultdict afterward:

counts = defaultdict(dict)
for piece, count in Counter(board.values()).items():
    counts[piece[0]][piece[1:]] = count


来源:https://stackoverflow.com/questions/65198660/is-this-code-for-making-a-nested-dictionary-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!