ok, I feel stupid, but there must be a better way than this! (finding name of unique key in dict)

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Jan 20 12:40:09 EST 2023


On Fri, 20 Jan 2023 at 17:30, Dino <dino at no.spam.ar> wrote:
>
> let's say I have this list of nested dicts:
>
> [
>    { "some_key": {'a':1, 'b':2}},
>    { "some_other_key": {'a':3, 'b':4}}
> ]
>
> I need to turn this into:
>
> [
>    { "value": "some_key", 'a':1, 'b':2},
>    { "value": "some_other_key", 'a':3, 'b':4}
> ]

You want both the key and the value so you can use items():

In [39]: L = [
    ...:    { "some_key": {'a':1, 'b':2}},
    ...:    { "some_other_key": {'a':3, 'b':4}}
    ...: ]

In [40]: [{"value": k, **m} for l in L for k, m in l.items()]
Out[40]:
[{'value': 'some_key', 'a': 1, 'b': 2},
 {'value': 'some_other_key', 'a': 3, 'b': 4}]

--
Oscar


More information about the Python-list mailing list