编写嵌套字典的代码正确吗? [英] Is this code for making a nested dictionary correct?

查看:50
本文介绍了编写嵌套字典的代码正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对本帖答案中给出的代码有一些问题:

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)

我想得到以下字典:

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注释说输出应该是每件的计数.可以使用 setdefault

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

这篇关于编写嵌套字典的代码正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆