Victor via plug on 6 Jul 2021 07:41:33 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Python nested dict data structure


>> # Add/inc_nstkv a value in a nested d
>> def inc_nstkv(d, key, subkey, value):
>>      d.setdefault(key, dict())
>>      d[subkey] = d.get(subkey, 1) + 1
*************************************
d[subkey] = d.get(subkey, 0) + value
*************************************
>### But that doesn't use `value`.  I guess I should have called
>### it accumulate and not increment.  This doesn't work:
>        d[subkey] = d.get(subkey, 1) += value
>### And I think it overwrites the region value, depending on order
>### (which will be unpredictable).

Oops, you're right that .get() should be using 0 as the default and
+value; fixed inline above. What led me to think of .setdefault() and
.get() was that you wrote their exact logic using other code plus the
explanation that you're pulling data from multiple sources where you
don't have a uniform dictionary output in mind. You can even eliminate
the functions you created entirely using .setdefault() and .get(), but
it's up to you if that diminishes readability. Example below.

> And I think it overwrites the region value, depending on order
I don't believe that's a problem, but maybe I'm not understanding your
expected output.

```
d = dict()
company = 'Acme Inc'

# If "company" key exists, add or set the "region" subkey; else the
"company" key should default to an empty dictionary then add or set
the "region" subkey.
d.setdefault(company, dict())['region'] = 'US'

# If "counter" key exists, get it's current value and add X; if
"counter" does not exist, return 0 as the default and add X.
d['counter'] = d.get('counter', 0) + 1
d['counter'] = d.get('counter', 0) + 2

print(d)
```
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug