autovivification

What is the best way to implement nested dictionaries?

折月煮酒 提交于 2020-01-07 02:31:25
问题 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. Moreover, I have to

How to create nested dictionaries with duplicate keys in python

半腔热情 提交于 2020-01-02 08:15:32
问题 I want to create data structure with nested dictionaries and duplicate keys. A detailed example is: data['State1']['Landon']['abc Area'] = 'BOB' data['State1']['Landon']['abc Area'] = 'SAM' data['State1']['Landon']['xyz Area'] = 'John' data['State2']['New York']['hjk Area'] = 'Ricky' for z in data['State1'].keys() , # I should get list ['Landon', 'Landon', 'Landon'] for y in data['State1']['Landon'].keys() , # I should get list ['abc Area', 'abc Area', 'xyz Area'] Currently to store the data

Ruby Autovivification

陌路散爱 提交于 2019-12-24 08:53:48
问题 I've been trying to use autovivification in ruby to do simple record consolidation on this: 2009-08-21|09:30:01|A1|EGLE|Eagle Bulk Shpg|BUY|6000|5.03 2009-08-21|09:30:35|A2|JOYG|Joy Global Inc|BUY|4000|39.76 2009-08-21|09:30:35|A2|LEAP|Leap Wireless|BUY|2100|16.36 2009-08-21|09:30:36|A1|AINV|Apollo Inv Cp|BUY|2300|9.15 2009-08-21|09:30:36|A1|CTAS|Cintas Corp|SELL|9800|27.83 2009-08-21|09:30:38|A1|KRE|SPDR KBW Regional Banking ETF|BUY|9200|21.70 2009-08-21|09:30:39|A1|APA|APACHE CORPORATION

How to implement autovivification for nested dictionary ONLY when assigning values?

我是研究僧i 提交于 2019-12-21 12:18:54
问题 TL;DR How can I get superkeys to be autovivified in a Python dict when assigning values to subkeys, without also getting them autovivified when checking for subkeys? Background: Normally in Python, setting values in a nested dictionary requires manually ensuring that higher-level keys exist before assigning to their sub-keys. That is, my_dict[1][2] = 3 will not reliably work as intended without first doing something like if 1 not in my_dict: my_dict[1] = {} Now, it is possible to set up a

How to change behavior of dict() for an instance

时间秒杀一切 提交于 2019-12-20 08:19:46
问题 So I'm writing a class that extends a dictionary which right now uses a method "dictify" to transform itself into a dict. What I would like to do instead though is change it so that calling dict() on the object results in the same behavior, but I don't know which method to override. Is this not possible, or I am I missing something totally obvious? (And yes, I know the code below doesn't work but I hope it illustrates what I'm trying to do.) from collections import defaultdict class

How to handle combination []+= for auto-vivifying hash in Ruby?

二次信任 提交于 2019-12-19 11:01:23
问题 In order to implement auto-vivification of Ruby hash, one can employ the following class class AutoHash < Hash def initialize(*args) super() @update, @update_index = args[0][:update], args[0][:update_key] unless args.empty? end def [](k) if self.has_key?k super(k) else AutoHash.new(:update => self, :update_key => k) end end def []=(k, v) @update[@update_index] = self if @update and @update_index super end def few(n=0) Array.new(n) { AutoHash.new } end end This class allows to do the following

How to handle combination []+= for auto-vivifying hash in Ruby?

天大地大妈咪最大 提交于 2019-12-19 11:01:12
问题 In order to implement auto-vivification of Ruby hash, one can employ the following class class AutoHash < Hash def initialize(*args) super() @update, @update_index = args[0][:update], args[0][:update_key] unless args.empty? end def [](k) if self.has_key?k super(k) else AutoHash.new(:update => self, :update_key => k) end end def []=(k, v) @update[@update_index] = self if @update and @update_index super end def few(n=0) Array.new(n) { AutoHash.new } end end This class allows to do the following

How can I access a deeply nested dictionary using tuples?

≯℡__Kan透↙ 提交于 2019-12-19 07:51:30
问题 I would like to expand on the autovivification example given in a previous answer from nosklo to allow dictionary access by tuple. nosklo's solution looks like this: class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value Testing: a = AutoVivification() a[1][2][3] = 4 a[1][3][3] = 5 a[1][2]['test'] = 6 print a Output: {1: {2: {

How can I access a deeply nested dictionary using tuples?

一曲冷凌霜 提交于 2019-12-19 07:51:10
问题 I would like to expand on the autovivification example given in a previous answer from nosklo to allow dictionary access by tuple. nosklo's solution looks like this: class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value Testing: a = AutoVivification() a[1][2][3] = 4 a[1][3][3] = 5 a[1][2]['test'] = 6 print a Output: {1: {2: {

Why does Perl autovivify in this case?

六眼飞鱼酱① 提交于 2019-12-17 20:15:29
问题 Why does $a become an arrayref? I'm not pushing anything to it. perl -MData::Dumper -e 'use strict; 1 for @$a; print Dumper $a' $VAR1 = []; 回答1: It is because the for loop treats contents of @$a as lvalues--something that you can assign to. Remember that for aliases the contents of the array to $_ . It appears that the act of looking for aliasable contents in @$a , is sufficient to cause autovivification, even when there are no contents to alias. This effect of aliasing is consistent, too.