autovivification

What's the best way to initialize a dict of dicts in Python? [duplicate]

和自甴很熟 提交于 2019-11-26 01:56:51
问题 This question already has answers here : What is the best way to implement nested dictionaries? (20 answers) Closed 6 years ago . A lot of times in Perl, I\'ll do something like this: $myhash{foo}{bar}{baz} = 1 How would I translate this to Python? So far I have: if not \'foo\' in myhash: myhash[\'foo\'] = {} if not \'bar\' in myhash[\'foo\']: myhash[\'foo\'][\'bar\'] = {} myhash[\'foo\'][\'bar\'][\'baz\'] = 1 Is there a better way? 回答1: class AutoVivification(dict): """Implementation of perl

What is the best way to implement nested dictionaries?

我与影子孤独终老i 提交于 2019-11-25 23:58:29
问题 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.