okpython
okpython

Reputation: 29

Python Dictionary of dictionaries

I'm using python3.

I have a dictionary

simulations = {
    'wk01' : '183',
    'wk02' : '170',
    'wk03' : '184',
}

and a separate dictionary containing a descriptive string

condition_old = {'slow'}

I am later joining simulations and condition_old to get a complete string.

simulations = {simulation : '-'.join([simulations[simulation],condition_old]) for simulation in simulations}

This results in output = {'wk01': '183-slow', 'wk02': '170-slow', 'wk03': '180-slow'}

I am then plotting data for each condition (e.g. slow). What I want to be able to do is to increase the number of values in the conditions e.g.:

condition_new = {'slow','med','fast}

and return a dictionary for each: condition01 = {'wk01': '183-slow', 'wk02': '170-slow', 'wk03': '180-slow'} condition02 = {'wk01': '183-med', 'wk02': '170-med', 'wk03': '180-med'} condition03 = {'wk01': '183-fast', 'wk02': '170-fast', 'wk03': '180-fast'}

What also needs to be considered is that the number of values in condition_new can vary, so I can't explicitly state 3 dictionary names to populate.

Maybe a dictionary within a dictionary would be sufficient. In the end I want to create 3 separate plots based on condition01 condition02 condition03.

Thanks

Upvotes: 0

Views: 90

Answers (1)

Jussi Nurminen
Jussi Nurminen

Reputation: 2408

You could use a loop and a dictionary comprehension. Something like:

simulations = {
    'wk01' : '183',
    'wk02' : '170',
    'wk03' : '184',
}

conditions = {'slow', 'med', 'fast'}

thedicts = dict()
for cond in conditions:
    thedicts[cond] = {k: f'{d}-{cond}' for k, d in simulations.items()}

Upvotes: 1

Related Questions