-5

I'm trying to find a code that transforms a list of lists into a dictionary. Lets say I have a list that is

list_one = [['id1', 'id2', id3', 'id4', 'id5'],
            ['1', 'Cat', '400', 'Fur', '50'],
            ['2', 'Dog', '500', 'Smelly', '60']]

The dictionary should have keys to number each list in dictionaries in this format

new_dict = {1.0: {'id1': 1,
                 'id2': 'Cat',
                 'id3': 400,
                 'id4': 'Fur',
                 'id5': 50},
            2.0: {'id1': 2,
                  'id2': 'Dog',
                  'id3': 500,
                  'id4': 'Smelly'
                  'id5': 60}

Can such a conversion be done in list comprehension or through a for loop?

user1821176
  • 1,141
  • 2
  • 18
  • 29
  • 6
    Seems very simple, so why not try implementing it yourself instead of spending potentially more time looking for ready-made code online? – Roope Nov 07 '18 at 21:40
  • 1
    in our target dict, why are the keys `1.0 ,2.0` etc. Why decimals? what is the physical significance? – Srini Nov 07 '18 at 21:42
  • To @Srini 's point, storing the keys as `floats` incurs extra overhead for no particular reason. Just store as `int`, it is smaller (from a data perspective) and makes it a bit easier to look up – C.Nivs Nov 07 '18 at 21:51

4 Answers4

3

a simple dict-comprehension using enumerate:

list_one = [['id1', 'id2', 'id3', 'id4', 'id5'],
            ['1', 'Cat', '400', 'Fur', '50'],
            ['2', 'Dog', '500', 'Smelly', '60']]

new_dict = {float(i): dict(zip(list_one[0], items)) 
            for i, items in enumerate(list_one[1:], start=1)}

print(new_dict)

results in

{1.0: {'id1': '1', 'id2': 'Cat', 'id3': '400', 'id4': 'Fur', 'id5': '50'}, 
 2.0: {'id1': '2', 'id2': 'Dog', 'id3': '500', 'id4': 'Smelly', 'id5': '60'}}
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
2

In your use case, the keys are the first list in your list, and the objects are the rest. You can zip them together and create that dictionary like so:

ks, objs = list_one[0], list_one[1:]

myobjects = {i: dict(zip(ks, l)) for i,l in enumerate(objs)}

zip will take the element-by-element pairs and create tuples like (x, y) and dict will make {x: y} from that tuple. The docs can be found here

C.Nivs
  • 12,353
  • 2
  • 19
  • 44
2

If you are okay with third party library pandas

import pandas as pd
{float(k):v for k,v in enumerate(pd.DataFrame(list_one[1:],columns=list_one[0]).to_dict('records'),1)}
mad_
  • 8,121
  • 2
  • 25
  • 40
1

The following should do the trick:

>>> new_dict = {float(i): {list_one[0][j]:val for j,val in enumerate(list_one[i])} for i in range(1,len(list_one))}
>>> new_dict
 {1.0: {'id1': '1', 'id2': 'Cat', 'id3': '400', 'id4': 'Fur', 'id5': '50'},
 2.0: {'id1': '2', 'id2': 'Dog', 'id3': '500', 'id4': 'Smelly', 'id5': '60'}}
Tim
  • 2,756
  • 1
  • 15
  • 31