0

I want to split line which has multiple ':' in it and form and dictionary: line:

'IP - internet : IPv4:225.138.42.248 IPv6:NA'

dictionary:

{
"IP - internet" : {
  "IPv4" : "225.138.42.248",
  "IPv6" : "NA"
}
}

I tried line.rsplit(':', 3) but unable to get exact dictionary any help will be highly appreciated.

Thanks,

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
prap4search
  • 5
  • 1
  • 4

1 Answers1

0

If the string will always be formatted like '<string 1> : <key1>:<value1> <key2>:<value2>', then you can use this:

s = 'IP - internet : IPv4:225.138.42.248 IPv6:NA'

l = s.split(' : ')

s1 = l[0]

l = l[1].split(' ')

k1, v1 = l[0].split(':')
k2, v2 = l[1].split(':')

d = {
  s1: {
    k1: v1,
    k2: v2,
  }
}

print d

Output:

{'IP - internet': {'IPv4': '225.138.42.248', 'IPv6': 'NA'}}

Alternatively, you can use a regular expression:

s = 'IP - internet : IPv4:225.138.42.248 IPv6:NA'

import re

pattern = r'([^:]+) : ([^:]+):([^:]+) ([^:]+):([^:]+)'

r = re.search(pattern, s)

s1, k1, v1, k2, v2 = (r.group(i) for i in range(1, 6))

d = {
  s1: {
    k1: v1,
    k2: v2,
  }
}

print d

Output:

{'IP - internet': {'IPv4': '225.138.42.248', 'IPv6': 'NA'}}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • @Pynchia `map(F, L)` returns a `map` object by applying the function `F` to the elements of `L` (a `map` object behaves almost like a list, you can index it, iterate over its elements, ...etc). – DjaouadNM Jun 08 '19 at 00:43
  • THanks for the suggestion ,actually my string is not fixed the one i gave is example.Generally i am looking for parser of a string which looks like ' : : :' . – prap4search Jun 10 '19 at 21:08
  • @prap4search It's still just a bunch of splitting, but you can also use a regular expression, check the edit to my answer. – DjaouadNM Jun 10 '19 at 22:16