简体   繁体   中英

Transform a list into a dictionary in python

I am new to python and have difficulties transforming some of the data types. I have a list of objects that have a lot of attributes and i want to create a better structure for them. The old_list is based 'Var' types that looks like this:

old_type.name='a_1_1'
old_type.value=3.0

The amount of indices and the type of the value may change :

[old_type('a_1_1',4),old_type('a_1_2',2),old_type('x_1',True)]

i would like to split the old name into letters and numbers and to create a new_data_structure to look ideally like this:

new_data_structure[0].letter = 'a'
new_data_structure[0].indices= [1,1]
new_data_structure[0].value = 4

new_data_structure[2].letter = 'x'
new_data_structure[2].indices= 1
new_data_structure[2].value  = True

and i spend quite some time, but i cant get it to work. i tried

 new_list= [[old_type[i].name.split('_'), \
                     old_type[i].vartype.value] for i in range(len(old_type))]

which creates wierdly deep lists ( new_list[0][0][0] for 'a') and is also only with indices. i tried to make a dict with

new_dict = {'letter': old_type[i].name.split('_'),  'value',old_type[i].value for i in range(len(old_type))}

but here the for seems not to loop over the comma seperated keywords and putting a for between every comma didn't work either.

Then i tried to explicitly loop over the different keys

for i in range(len(old_type)):
    new_dict[i][letter] = old_type[i].name.split('_')
    new_dict[i][value] = old_type[i].value

but this overwrites each time and leaves only the last letter and value in new_dict. I feel like i am making this way harder than it should be.

So in total: Is there a way to transform attributes of a list of objects into a dict (list of dicts?) with keywords as said attributes?

Additional question: Isn't there something like substr('_') i python that qould only return the string part until the first '_'?

Thank you

You could use namedtuple and split and make a new structure like this,

>>> class OldType(object):
...   def __init__(self, val1, val2):
...     self.val1 = val1
...     self.val2 = val2
...                                                                                                                                                             
>>>                                                                                                                                       
>>> from collections import namedtuple                                                                                                                                                 
>>>                                                                                                                                                  
>>> cus_struct = namedtuple('CustomStruct', ['letter', 'indices', 'value'])
>>> x = [OldType('a_1_1',4), OldType('a_1_2',2), OldType('x_1',True)]                                               
>>> [y.val1.partition('_') for y in x]
[('a', '_', '1_1'), ('a', '_', '1_2'), ('x', '_', '1')]                                                                                              
>>> 
>>>                                                                                                                                                  
>>> new_ds = []
>>> for y in x:
...   letter, _, indices = y.val1.partition('_')
...   indices = [int(k) for k in indices.split('_')]
...   new_ds.append(cus_struct(letter, indices, y.val2))
... 
>>> new_ds[0].letter
'a'
>>> new_ds[0].indices
[1, 1]
>>> new_ds[0].value
4
>>>
>>> for item in new_ds:
...   print(item.letter, item.indices, item.value)
... 
('a', [1, 1], 4)
('a', [1, 2], 2)
('x', [1], True)

This is doable using a simple list comprehension:

new_dictlist = [
    { 'letter': i.name.split('_')[0], 'value': i.value }
    for i in old_type
]

Since split returns a list, use [0] to access the first part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM