Reputation: 650
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]
Upvotes: 3
Views: 8856
Reputation: 113934
>>> 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]}
Upvotes: 5
Reputation: 144
line = "David 12 14 15"
parts = line.split()
lineDict = {}
lineDict[parts[0]] = parts[1] + " " + parts[2] + " " + parts[3]
Upvotes: 0
Reputation: 90989
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.
Upvotes: 4
Reputation: 114035
In [2]: line = "David 12 14 15"
In [3]: answer = {}
In [4]: key, vals = line.split(None, 1)
In [5]: answer[key] = [int(i) for i in vals.split()]
In [6]: answer
Out[6]: {'David': [12, 14, 15]}
In [7]: answer['David']
Out[7]: [12, 14, 15]
Upvotes: 1