# 实现嵌套字典的最佳方法是什么？ - What is the best way to implement nested dictionaries?

10/14 16:05

### 问题：

I have a data structure which essentially amounts to a nested dictionary.我有一个基本上相当于嵌套字典的数据结构。 Let's say it looks like this:假设它看起来像这样：

{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36}}}


Now, maintaining and creating this is pretty painful;现在，维护和创建它是非常痛苦的； every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks.每次我有一个新的州/县/专业时，我都必须通过令人讨厌的 try/catch 块创建下层词典。 Moreover, I have to create annoying nested iterators if I want to go over all the values.此外，如果我想查看所有值，我必须创建烦人的嵌套迭代器。

I could also use tuples as keys, like such:我也可以使用元组作为键，例如：

{('new jersey', 'mercer county', 'plumbers'): 3,
('new jersey', 'mercer county', 'programmers'): 81,
('new jersey', 'middlesex county', 'programmers'): 81,
('new jersey', 'middlesex county', 'salesmen'): 62,
('new york', 'queens county', 'plumbers'): 9,
('new york', 'queens county', 'salesmen'): 36}


This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (eg if I just want to go state-by-state).这使得迭代值变得非常简单和自然，但在语法上做聚合和查看字典的子集（例如，如果我只想逐个状态）在语法上更痛苦。

Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy.基本上，有时我想将嵌套字典视为平面字典，有时我想将其视为复杂的层次结构。 I could wrap this all in a class, but it seems like someone might have done this already.我可以把这一切都包装在一个班级中，但似乎有人可能已经这样做了。 Alternatively, it seems like there might be some really elegant syntactical constructions to do this.或者，似乎有一些非常优雅的语法结构可以做到这一点。

How could I do this better?我怎么能做得更好？

Addendum: I'm aware of setdefault() but it doesn't really make for clean syntax.附录：我知道setdefault()但它并没有真正实现干净的语法。 Also, each sub-dictionary you create still needs to have setdefault() manually set.此外，您创建的每个子词典仍然需要手动设置setdefault()

0
0 收藏

0 评论
0 收藏
0