Format list of list sub elements keeping structure.

Peter Otten __peter__ at web.de
Tue Jul 24 04:19:05 EDT 2018


Sayth Renshaw wrote:

> I have data which is a list of lists of all the full paths in a json
> document.
> 
> How can I change the format to be usable when selecting elements?

How do you want to select these elements?

myjson = ...
path = "['foo']['bar'][42]"
print(eval("myjson" + path))

?

Wouldn't it be better to keep 'data' as is and use a helper function like

def get_value(myjson, path):
    for key_or_index in path:
        myjson = myjson[key_or_index]
    return myjson

path = ['foo', 'bar', 42]
print(get_value(myjson, path))

?

> data = [['glossary'],
>  ['glossary', 'title'],
>  ['glossary', 'GlossDiv'],
>  ['glossary', 'GlossDiv', 'title'],
>  ['glossary', 'GlossDiv', 'GlossList'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'ID'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'SortAs'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossTerm'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'Acronym'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'Abbrev'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef', 'para'],
>  ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef',
>  ['GlossSeeAlso'], 'glossary', 'GlossDiv', 'GlossList', 'GlossEntry',
>  ['GlossDef', 'GlossSeeAlso', 0], 'glossary', 'GlossDiv', 'GlossList',
>  ['GlossEntry', 'GlossDef', 'GlossSeeAlso', 1], 'glossary', 'GlossDiv',
>  ['GlossList', 'GlossEntry', 'GlossSee']]
> 
> I am trying to change it to be.
> 
> [['glossary'],
>  ['glossary']['title'],
>  ['glossary']['GlossDiv'],
> ....]
> 
> Currently when I am formatting I am flattening the
> structure(accidentally).
> 
> for item in data:
>     for elem in item:
>         out = ("[{0}]").format(elem)
>     print(out)
> 
> Which gives
> 
> [glossary]
> [title]
> [GlossDiv]
> [title]
> [GlossList]
> [GlossEntry]
> [ID]
> [SortAs]
> [GlossTerm]
> [Acronym]
> [Abbrev]
> [GlossDef]
> [para]
> [GlossSeeAlso]
> [0]
> [1]
> [GlossSee]
> 
> 
> Cheers
> 
> Sayth




More information about the Python-list mailing list