ok, I feel stupid, but there must be a better way than this! (finding name of unique key in dict)
Rob Cliffe
rob.cliffe at btinternet.com
Fri Jan 20 13:44:17 EST 2023
On 20/01/2023 15:29, Dino 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}
> ]
Assuming that I believe the above, rather than the code below, this works:
listOfDescriptors = [
{ ** (L := list(D.items())[0])[1], **{'value' : L[0] } }
for D in origListOfDescriptors]
I believe that from Python 3.9 onwards this can be written more
concisely as:
listOfDescriptors = [
{ (L := list(D.items())[0])[1] } | {'value' : L[0] }
for D in origListOfDescriptors] # untested
Best wishes
Rob Cliffe
>
> I actually did it with:
>
> listOfDescriptors = list()
> for cd in origListOfDescriptors:
> cn = list(cd.keys())[0] # There must be a better way than this!
> listOfDescriptors.append({
> "value": cn,
> "type": cd[cn]["a"],
> "description": cd[cn]["b"]
> })
>
> and it works, but I look at this and think that there must be a better
> way. Am I missing something obvious?
>
> PS: Screw OpenAPI!
>
> Dino
More information about the Python-list
mailing list