Search code examples
pythondictionarynesteddictionary-comprehension

Nested dictionary comprehension combined with using values as key:value


I have a data structure in the following format:

dict = {
        garbage1:{currency: 'JPY', maturity: 20apr2021, yield:-0.50%}, 
        garbage2:{currency: 'JPY', maturity: 30mar2022, yield:-0.2%},
        garbage3:{currency: 'EUR', maturity: 15may2021, yield: +0.1%}
       }

I would like this to become

new_dict = {
            'JPY': {20apr2021:-0.50%, 30mar2022,-0.20%},
            'EUR': {15may2021:+0.1%}
           }

So i'm trying to use nested dictionary comprehension and combine that with turning the values into a key value. Struggling. This is the furthest I can get thus far:

new_dict = {outer_val: {inner_val["maturity"]: inner_val["yield"] for inner_key, inner_val in outer_val.items()}
            for outer_key, outer_val in dict.items()}

Solution

  • You can do this with loops:

    new_dict = {}
    for value in dict.values():
        if value['currency'] not in new_dict:
            new_dict[value['currency']] = [value['maturity']]
        else:
            new_dict[value['currency']].append(value['maturity'])
    

    Also note:

    1. In the new_dict you are trying to store dictionaries as values but that looks as a list (no keys or values). So in the code above I used usual lists.
    2. I do not know what these are: currency, maturity etc. So I used strings instead