[英]Is this code for making a nested dictionary correct?
我对这篇文章的答案中给出的代码有一些问题: 我可以在 python 中对具有多个条件的 if-else 语句使用嵌套的 for 循环吗?
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)
我想得到以下字典:
count = {'b': {'king': 1, 'pawn': 3, 'bishop': 1},
'w': {'king': 1, 'rook': 1, 'queen': 1}}
收到错误:
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'
OP 评论说 output 应该是每件的计数。 这可以使用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}}
您的代码中的问题是,当您访问nested[k[0]]
时,您希望nested
已经拥有此键,并且您希望相应的值是一个字典。
解决这个问题的最简单方法是使用defaultdict(dict) ,它会在需要时动态创建它:
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'}})
如果您只需要计数,请使用collections.Counter
,然后使用collections.defaultdict
拆分结果:
counts = defaultdict(dict)
for piece, count in Counter(board.values()).items():
counts[piece[0]][piece[1:]] = count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.