制作嵌套字典的代码正确吗?

2024-05-23 14:03:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这篇文章的答案中给出的代码有一些问题: 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)

我想得到以下词典:

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'

Tags: 答案代码inboardloopanforuse
3条回答

如果只需要计数,请使用collections.Counter,然后使用collections.defaultdict分割结果:

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

OP评论说输出应该是每件物品的数量。可以使用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已经有这个键,并且您希望相应的值是dict

解决此问题的最简单方法是使用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'}})

相关问题 更多 >