Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string within a list to create key-value pairs in Python

Tags:

python

string

I have a list that looks like this:

[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'] 

And I want to split this list by '=' so that everything on the left side will become keys and on the right, values.

{      'abc':'lalalla',     'appa':'kdkdkdkd',     'kkakaka':'oeoeo' } 
like image 502
Vor Avatar asked Oct 05 '12 05:10

Vor


People also ask

How do you split a string into an item in a list Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a key value pair in Python?

Method 1: Split dictionary keys and values using inbuilt functions. Here, we will use the inbuilt function of Python that is . keys() function in Python, and . values() function in Python to get the keys and values into separate lists.

How do you split a string into multiple variables in Python?

Unpack the values to split a string into multiple variables, e.g. a, b = my_str. split(' ') . The str. split() method will split the string into a list of strings, which can be assigned to variables in a single declaration.

How do you split data in a list in Python?

To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.


1 Answers

a = [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'] d = dict(s.split('=') for s in a) print d   Output: {'kkakaka': 'oeoeoeo', 'abc': 'lalalla', 'appa': 'kdkdkdkd'} 

http://codepad.org/bZ8lGuHE

like image 59
Demian Brecht Avatar answered Sep 23 '22 17:09

Demian Brecht