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]
>>> s = 'David 12 14 15'.split()
>>> {s[0]:[int(y) for y in s[1:]]}
{'David': [12, 14, 15]}
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]}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With