0

There have been similar questions but I've not quite been able to get it right - apologies for duplications. What I would like to do is create dataframe names inside a dictionary based on variables as I iterate.

d = {}
market = 'SPX'
datatype = 'prices'

for j in range(10):
    year = 2010+j
    start = str(year) + '-01-01'
    end = str(year+2) + '-01-01'
        
    d['{market}_{datatype}_from_{start}_to{end}'] = 'foo'

I would like for the elements of the dictionary to be called

spx_prices_from_2010-01-01_to_2012-01-01
spx_prices_from_2011-01-01_to_2013-01-01
...

Thank you very much in advance

1
  • You have forgotten your string formatting. Change d['{market}_{datatype}_from_{start}_to{end}'] to d[f'{market}_{datatype}_from_{start}_to{end}'] Commented Mar 16, 2021 at 0:21

1 Answer 1

2

If you're using Python 3, you can use f-strings:

d = {}
market = 'SPX'
datatype = 'prices'

for j in range(10):
    year = 2010+j
    start = str(year) + '-01-01'
    end = str(year+2) + '-01-01'
        
    d[f"{market}_{datatype}_from_{start}_to_{end}"] = 'foo'

Alternatively, you can use str's format method.

Sign up to request clarification or add additional context in comments.

6 Comments

Woha that was easy. Thank you so much!!
1 more quick question if I haven't imposed too much already: is there an easy way of assigning the name of the dictionary itself - changing the name from d to "SPX_Prices" based on the variables?
I'd avoid that and just use a collection (e.g. d['SPX']['prices'] = ...).
Thanks, but that doesn't do it... I think. I want to iterate through markets and datatypes - and for each create a dictionary of dataframes. So I want to name these dictionaries dynamically. Again, I'm super grateful
The dictionaries will just be embedded in an outer dictionary. You can write: ``` for market in markets: for datatype in datatypes: d["{}_{}".format(market, datatypes)] = ... ``` You can then access all the dictionaries with d.values().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.