Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a space separated string to a dictionary element in Python

Tags:

python

string

How I can convert the following string to a dictionary element in python?

David 12 14 15

Dictionary element will be something like:

[David] => [12, 15, 20]
like image 931
qasimzee Avatar asked Dec 08 '25 18:12

qasimzee


2 Answers

Quick answer

>>> s = 'David 12 14 15'.split()
>>> {s[0]:[int(y) for y in s[1:]]}
{'David': [12, 14, 15]}

Step by step details

First, we split the string on white space:

>>> s = 'David 12 14 15'.split()
>>> s
['David', '12', '14', '15']

Now, we need two parts of this list. The first part will be the key in our dictionary:

>>> s[0]
'David'

The second part will be the value:

>>> s[1:]
['12', '14', '15']

But, we want the values to be integers, not strings, so we need to convert them:

>>> [int(y) for y in s[1:]]
[12, 14, 15]

One can make dictionaries by specifying keys and values, such as:

>>> {'key':[1,2]}
{'key': [1, 2]}

Using our key and value produces the dictionary that we want:

>>> {s[0]:[int(y) for y in s[1:]]}
{'David': [12, 14, 15]}
like image 96
John1024 Avatar answered Dec 11 '25 07:12

John1024


You can split the string using str.split() , and then use list.pop(0) to pop the first element to get the key and set the rest of the split list as the value. Example -

>>> d = {}
>>> s = 'David 12 14 15'
>>> ssplit = s.split()
>>> key = ssplit.pop(0)
>>> d[key] = ssplit
>>> d
{'David': ['12', '14', '15']}

If you want the elements as int , you can also use map before setting the value to dictionary -

>>> d[key] = list(map(int, ssplit))
>>> d
{'David': [12, 14, 15]}

For Python 2.x, you do not need the list(..) as map() in Python 2.x already returns a list.

like image 23
Anand S Kumar Avatar answered Dec 11 '25 09:12

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!