Home > Software engineering >  Flatten out keys into a single key and splitting their values by lists
Flatten out keys into a single key and splitting their values by lists

Time:10-04

Suppose I have a dictionary like so:

{'a':['data', 1, 2, 3],
 'b':['data2', 4, 3, 2, 1, 0],
 'c':['data3', 3, 4, 5, 6]}

And I wanted to to be compressed likeso:

{'letters':['a','b','c'],
 'values':[['data', 1, 2, 3], ['data2', 4, 3, 2, 1, 0], ['data3', 3, 4, 5, 6]]}

Where letters and values can be any arbitrary names set for the key.

CodePudding user response:

Assuming:

d = {'a':['data', 1, 2, 3],
     'b':['data2', 4, 3, 2, 1, 0],
     'c':['data3', 3, 4, 5, 6]}

you can use:

out = {'letters': list(d.keys()),
       'values':  list(d.values())
       }

output:

>>> out
{'letters': ['a', 'b', 'c'],
 'values': [['data', 1, 2, 3], ['data2', 4, 3, 2, 1, 0], ['data3', 3, 4, 5, 6]]
}
  • Related