You have a bunch a variables that you want to assign to, where the names might look like these: grant0, funding97, grant42, grant26, funding27
So instead of having seperate variables, put the data all together into one variable that stores them like this:
source = {'grant': [], 'funding': []'}
So instead of accessing the data from the variable grant0
, you can do source['grant'][0]
. As another example, instead of using funding97
, use source['funding'][97]
If I understand your question correctly, this may be what you want:
income_brackets = [(0, 25000), (25000, 50000)]
source = {'grant': [], 'funding': []}
#Hard to understand one-liner
#source = {key: [median(df.query('income > {} and income < {}'.format(lower, upper))[key]) for lower, upper in income_brackets] for key in source}
#Easy to understand three-liner
for lower, upper in income_brackets:
for key in source:
source[key].append(median(df.query('income > {} and income < {}'.format(lower, upper))[key]))
How list comprehensions work:
>>> foo = []
>>> for i in range(10):
foo.append(i)
>>> foo
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> bar = [i for i in range(10)]
>>> bar
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionary comprehensions work similar to list comprehensions, except you have key value pairs.
Step-by-step explanation of my solution using the interpreter:
>>> income_brackets = [(0, 25000), (25000, 50000)]
>>> source = {'grant': [], 'funding': []}
>>> for lower, upper in income_brackets:
print(lower, upper)
0 25000
25000 50000
>>> for lower, upper in income_brackets:
for key in source:
print(lower, upper, key)
0 25000 grant
0 25000 funding
25000 50000 grant
25000 50000 funding
>>> for lower, upper in income_brackets:
for key in source:
source[key].append(5)
>>> source
{'grant': [5, 5], 'funding': [5, 5]}
>>> source['grant'][0]
5
>>> source['grant'][1]
5
>>> source['funding'][0]
5
>>> source['funding'][1]
5