vendredi 16 juillet 2021

Converting nested List to Dictionary | Python

I have made a list comprehension that generates mock fingerprint data.

import random

val = [[hand, [digit, [[random.randint(1, 250) for i in range(0, 8)] for j in range(0, 4)]]] for hand in ['Left', 'Right'] for digit in ['Thumb', 'Index', 'Middle', 'Ring', 'Little']]
val
>>> [['Left',
  ['Thumb',
   [[247, 115, 74, 161, 47, 31, 231, 34],
    [246, 52, 1, 160, 196, 65, 4, 118],
    [128, 219, 128, 140, 207, 2, 156, 226],
    [127, 61, 56, 151, 169, 122, 117, 105]]]]
...
 ['Right',
  ['Thumb',
   [[229, 222, 138, 230, 86, 119, 201, 209],
    [106, 238, 191, 15, 214, 134, 77, 145],
    [186, 174, 81, 143, 138, 5, 54, 148],
    [176, 85, 205, 235, 228, 204, 91, 17]]]]

Note: "digit" means finger name.

Based on this list output, I would like to convert it to a dictionary of the below structure.

I've been unable to make a dictionary comprehension that would yield the desired output:

{
  "Left":
  {
    "Thumb": [...],
    "Index": [...],
    "Middle": [...],
    "Ring": [...],
    "Little": [...]
  },
  "Right":
  {
    "Thumb": [...],
    "Index": [...],
    "Middle": [...],
    "Ring": [...],
    "Little": [...]
  }
}

Note: I understand my above dictionary "output" is somewhat incorrect.


I'm using Jupyter Notebooks. Best attempt:

output = {hand: {digit: matrix for i in val for hand in val[i] for digit in hand}}
output
>>> ---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-46-500095a8cf85> in <module>
----> 1 output = {hand: {digit: matrix for i in val for hand in val[i] for digit in hand}}
      2 output

NameError: name 'hand' is not defined



Aucun commentaire:

Enregistrer un commentaire