user1589244
user1589244

Reputation: 445

string to list of dictionaries (python)

I have a string that needs to be split 3 ways and then into a list of dictionaries.

given_string = 'name:mickey,age:58|name:minnie,age:47,weight:60' 

data = []

data = [value.split(',') for value in given_string.split('|')]

data = [['name:mickey', 'age:58'], ['name:minnie', 'age:47', 'weight:60']]

Now I want to split this one more time on the ':' and have the data contain a list of two dictionaries so that when I input say data[1][age], I get 47.

Basically, I think I want this for it to work:

data = [{'name': 'mickey', 'age': '58}, {'name': 'minnie', 'age': '47', 'weight': '60'}] 

I believe that ultimately, data should be a list of dictionaries but once I split the string into two lists, I get confused in splitting it on the ':' and then converting the sublists to a dictionary.

Upvotes: 1

Views: 4662

Answers (3)

raton
raton

Reputation: 428

 given_string = 'name:mickey,age:58|name:minnie,age:47,weight:60' 
 data = [value.split(',') for value in given_string.split('|')]

 y=[] # make a empty list
 for i in data:
     z={}
     for v in range(len(i)):
         b=i[v].split(":")      #  ['name", "mickey', 'age","58"]
         z[b[0]]=b[1]           # adding keys and values in dictionary z  
     y.append(z)                # adding dictionary to the list

Upvotes: 0

JBernardo
JBernardo

Reputation: 33397

You can do with a simple list comprehension

>>> [dict(x.split(':') for x in parts.split(',')) 
     for parts in given_string.split('|')]
[{'age': '58', 'name': 'mickey'}, {'age': '47', 'name': 'minnie', 'weight': '60'}]

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Nest harder.

>>> [ dict(y.split(':') for y in x.split(',')) for x in 'name:mickey,age:58|name:minnie,age:47,weight:60'.split('|')]
[{'age': '58', 'name': 'mickey'}, {'age': '47', 'name': 'minnie', 'weight': '60'}]

Upvotes: 3

Related Questions