0

Let's say I have a function that returns a numeric value called get_miles_sum_by_region(). It takes several parameters (region, tier, study_type):

region = 1
reg_tier1_approx = get_miles_sum_by_region(region, 'TIER 1', 'Approximate')
reg_tier2_approx = get_miles_sum_by_region(region, 'TIER 2', 'Approximate')
reg_tier3_approx = get_miles_sum_by_region(region, 'TIER 3', 'Approximate')
reg_tier4_approx = get_miles_sum_by_region(region, 'TIER 4', 'Approximate')
reg_tier1_detailed = get_miles_sum_by_region(region, 'TIER 1', 'Detailed')
reg_tier2_detailed = get_miles_sum_by_region(region, 'TIER 2', 'Detailed')
reg_tier3_detailed = get_miles_sum_by_region(region, 'TIER 3', 'Detailed')
reg_tier4_detailed = get_miles_sum_by_region(region, 'TIER 4', 'Detailed')

Basically, I want to create a dictionary like this:

region_dict = {1: {'Detailed': {'Tier1': 123.547, 'Tier2': 69.6,...}, 'Approximate': {'Tier1': 459.0032, 'Tier2': 540.112,...} } }

I've tried using setdefault() but I don't quite have the setup right:

region_dict = dict()
region_dict.setdefault(region, list('Detailed')).append(reg_tier1_detailed)

Any suggestion on setting this up correctly?

gwydion93
  • 1,681
  • 3
  • 28
  • 59

1 Answers1

1

I'm not sure how dict.setdefault would work in this situation, but I know you could use nested dict comprehensions:

region_dict = {
    region: {
        study_type: {
            f'Tier {i}':
            get_miles_sum_by_region(region, f'TIER {i}', study_type)
            for i in range(1, 5)
            }
        for study_type in ['Detailed', 'Approximate']
        }
    for region in [1]
    }
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • While this is not exactly what I expected, it seems to work. Follow up question; now that I essentially have a dictionary like this: `{1: {'Detailed': {'Tier 1':1732.8399404549093,'Tier 2': 3383.393797910064,'Tier 3':788.8760088460933,'Tier 4': 0.0},'Approximate': {'Tier 1': 0.0,'Tier 2': 1018.6503699587715,'Tier 3': 3009.3490080476213,'Tier 4': 0.0}}}`, suppose I wanted to add more regions (with the same subobjects) to the main dictionary? I am trying to set this up as a function, so once the main dictionary is created, I want to loop through and append new regions. – gwydion93 Nov 12 '19 at 02:30
  • @gwydion93 There are multiple ways to do that and which one is best depends on your use case. For example you could set `region = 2` then assign to `region_dict[region]` using my code for the first level nested dict. Or build a new dict for each region and see [How do I merge two dictionaries in a single expression?](https://stackoverflow.com/q/38987/4518341) – wjandrea Nov 12 '19 at 02:43