convert a space separated string to a dictionary element in python

  • Last Update :
  • Techknowledgy :

Quick answer

>>> 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'

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]
}

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]
   }
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]
line = "David 12 14 15"
parts = line.split()
lineDict = {}
lineDict[parts[0]] = parts[1] + " " + parts[2] + " " + parts[3]

Suggestion : 2

The call s.split() splits the string s into words separated by whitespace (space, tabulator, or newline): , Splitting a string s into words separated by a text t can be done by s.split(t). For example, we may split with respect to colon: , The opposite of the split method is join, which joins elements in a list of strings with a specified delimiter in between. That is, the following two types of statements are inverse operations: , As an illustration of the usefulness of split and join, we want to remove the first two words on a line. This task can be done by first splitting the line into words and then joining the words of interest:

>>> s = 'Berlin: 18.4 C at 4 pm' >>>
   s[8: ] # from index 8 to the end of the string '18.4 C at 4 pm' >>>
   s[8: 12] # index 8, 9, 10 and 11(not 12!)
'18.4'
>>> s[8: -1]
'18.4 C at 4 p' >>>
s[8: -8]
'18.4 C'
>>> s.find('Berlin') # where does 'Berlin'
start ?
   0 >>>
   s.find('pm')
20
   >>>
   s.find('Oslo') # not found -
   1
>>> 'Berlin' in s:
   True >>>
   'Oslo' in s:
   False
>>>
if 'C' in s:
   ...print 'C found'
   ...
   else:
      ...print 'no C'
      ...
      C found
>>> s.startswith('Berlin')
True
   >>>
   s.endswith('am')
False

Suggestion : 3

Using Generator Expressions,Finally, in the last example we will discuss how generator expressions can be used.,Python Design Patterns,In this tutorial, we explored the conversion methods of string to the dictionary.

String_1 is {
   "subj1": "Computer Science",
   "subj2": "Physics",
   "subj3": "Chemistry",
   "subj4": "Mathematics"
}
The resultant dictionary is {
   'subj1': 'Computer Science',
   'subj2': 'Physics',
   'subj3': 'Chemistry',
   'subj4': 'Mathematics'
}
String_1 is  subj1 - 10 , subj2 - 20, subj3 - 25, subj4 - 14
The resultant dictionary is:  {'subj1': 10, 'subj2': 20, 'subj3': 25, 'subj4': 14}
<class 'dict'>