[Python] How to concatenate nested items in dictionary?

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I have a nested dictionary and I want to concatenate the items of the nested dictionaries:

    import random
    nested_dict = {
    k: {
    'val0': random.sample(range(100), 2),
    'val1': random.sample(range(100), 2),
    }
    for k in 'abcd'
    }


    I can make it with a double-loop like this:

    from collections import defaultdict

    dp_dict= defaultdict(list)

    for v in nested_dict.values():
    for k, v_nested in v.items():
    dp_dict[k].append(v_nested)
    val0 = dp_dict['val0']
    val1 = dp_dict['val1']


    is there a more Pythonic/elegant way to do it?

    NB
    one solution is to use Pandas, however, this solution is quite ineficcient (X300 slower)

    import pandas as pd
    val0, val1 = pd.DataFrame(nested_dict).loc[['val0', 'val1']].values

    Continue reading...

Compartilhe esta Página