How to initialize nested dictionaries in Python
Date : March 29 2020, 07:55 AM
around this issue Use setdefault: format_to_year_to_value_dict.setdefault(format_str, {})[year] = value
format_to_year_to_value_dict = defaultdict(dict)
...
format_to_year_to_value_dict[format_str][year] = value
def example(format_str, year, value):
format_to_year_to_value_dict = {}
format_to_year_to_value_dict.setdefault(format_str, {}).setdefault(year, []).append(value)
def example(format_str, year, value):
format_to_year_to_value_dict = defaultdict(lambda: defaultdict(list))
format_to_year_to_value_dict[format_str][year].append(value)
tree = lambda: defaultdict(tree)
my_tree = tree()
my_tree['a']['b']['c']['d']['e'] = 'whatever'
|
Merge two dictionaries with nested dictionaries into new one, summing same keys and keeping unaltered ones in Python
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Seems like a use-case for a defaultdict of a defaultdict of int ... The basic idea is that when you come across a key that isn't in the top-level defaultdict, you add the key (with an associated defaultdict(int) to store the date -> integer map as the value). When you come across a date which isn't in the nested dict, the defaultdict(int) will add the date with a default value of 0 (since int() called with no arguments returns 0). from collections import defaultdict
output = defaultdict(lambda: defaultdict(int))
for d in (dict1, dict2):
for key, values_dict in d.items():
for date, integer in values_dict.items():
output[key][date] += integer
output.default_factory = None
for default_date_dict in output.values():
default_date_dict.default_factory = None
|
Python: Nested dictionaries: getting string(key+value) as values then swap with keys, combining dictionaries
Tag : python , By : Frank Bradley
Date : March 29 2020, 07:55 AM
like below fixes the issue Say I have this 3 dictionaries: , This could do the trick: d4 = {}
for k, v in d2.items():
d4[k] = {}
for k2, v2 in v.items():
try:
if v2 not in d4[k]:
d4[k][v2] = [k2 + ' = ' + d3[k][k2]]
else:
d4[k][v2].append(k2 + ' = ' + d3[k][k2])
except KeyError:
# this means k2 is a typo in d2; skip
assert k in d3 # be sure that a missing name isn't causing the KeyError
# you only need to use pass when you don't have any other operations in the scope
for k, v in d1.items():
for k2, v2 in v.items():
d4[k][k2] = v2
print(d4 == d123_new)
# -> True
|
Given three nested dictionaries, sort the top two nested dictionaries from a value in the innermost dictionary?
Date : March 29 2020, 07:55 AM
I wish this helpful for you I am trying to sort both the outermost dictionary and the "middle" dictionary by the value of "Cal" (highest first) in the innermost dictionary. I would like to accomplish this using an OrderedDict. , this should work: from collections import OrderedDict
od = OrderedDict()
for food, dct in sorted(foods.items(),
key=lambda x: max(int(y['Cal']) for y in x[1].values()),
reverse=True):
od[food] = OrderedDict()
subod = od[food]
for subkey, subdct in sorted(dct.items(), key=lambda x: int(x[1]['Cal']),
reverse=True):
subod[subkey] = subdct
# from pprint import pprint
# pprint(od)
OrderedDict([('Cheesecake',
OrderedDict([('ExtraSweet', {'Cal': '18000', 'Taste': '16'}),
('Sweet', {'Cal': '12000', 'Taste': '17'})])),
('IceCream',
OrderedDict([('Chocolate', {'Cal': '2000', 'Taste': '9'}),
('Vanilla', {'Cal': '1000', 'Taste': '11'})])),
('Pizza',
OrderedDict([('Pesto', {'Cal': '200', 'Taste': '9'}),
('Cheese', {'Cal': '100', 'Taste': '11'})])),
('Apple',
OrderedDict([('Green', {'Cal': '20', 'Taste': '6'}),
('Red', {'Cal': '1', 'Taste': '4'})]))])
|
How to unpack complicated nested column (list of dictionaries of dictionaries) in Python? [Twitter Ads API]
Date : March 29 2020, 07:55 AM
it helps some times You should be able to pass the dictionary directly to the dataframe constructor: foo = pd.DataFrame(df['id_data'][0]['metrics'])
foo.iloc[:3, :4]
app_clicks card_engagements carousel_swipes clicks
0 6 6 None 18
1 28 28 None 33
2 13 13 None 32
|