Splitting a Semicolon-Separated String to a Dictionary, in Python

Splitting a semicolon-separated string to a dictionary, in Python

There's no builtin, but you can accomplish this fairly simply with a generator comprehension:

s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))

[Edit] From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):

>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"

>>> dict(csv.reader([item], delimiter='=', quotechar="'").next()
for item in csv.reader([s], delimiter=';', quotechar="'").next())

{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}

Depending on the exact structure of your format, you may need to write your own simple parser however.

Convert a comma separated string of key values pairs to dictionary

How about:

{k: float(v) for k, v in [i.split(':') for i in s.split(',')]}

How can I split values of a dictionary by comma?

You are near the solution, take a look to this code.

games = {
"1":"GTA V,FarCry 5",
"2":"Watchdogs II,South Park: The Stick of Truth",
"3":"For Honor,The Forest,South Park: The Fractured but whole"
}

for games_key in games:
games[games_key] = games[games_key].split(",")

print(games)

#OUTPUT: {'1': ['GTA V', 'FarCry 5'], '2': ['Watchdogs II', 'South Park: The Stick of Truth'], '3': ['For Honor', 'The Forest', 'South Park: The Fractured but whole']}

Logic:

  • Iterate over the dictionary key
  • Write at the dictionary key the value splitted

Take a look to the dictionary reference

Converting colon separated list into a dict?

If I understand your requirements correctly, then you can use the following one-liner.

def list_to_dict(rlist):
return dict(map(lambda s : s.split(':'), rlist))

Example:

>>> list_to_dict(['alpha:1', 'beta:2', 'gamma:3'])
{'alpha': '1', 'beta': '2', 'gamma': '3'}

You might want to strip() the keys and values after splitting in order to trim white-space.

return dict(map(lambda s : map(str.strip, s.split(':')), rlist))

How do I convert strings separated by comma into dictionary in python?

I'll assume that you have a file or file-like object input containing the input lines you posted. Then you can use this code to parse it into a dictionary like this:

output = {}
for line in input:
key, values = line.strip().split('=', 1)
data = values.split(',')
output['record' + key[5:]] = dict(name=data[0], addr=data[1], phone=data[2])

However, if you don't actually need the number from input1 etc., consider using a list as the top-level object:

output = []
for line in input:
values = line.strip().split('=', 1)[1]
data = values.split(',')
output.append(dict(name=data[0], addr=data[1], phone=data[2]))

Splitting a semicolon-separated with equal in a string

If you have python installed, I recommend using its interactive repl

With the repl you can run the parts of your program step by step:

  1. s.split(";") will give you ['Name1=Value1', 'Name2=Value2', 'Name3=Value3']
['Name1=Value1', 'Name2=Value2', 'Name3=Value3']

  1. item.split("=") for item in s.split(";") will give you a python generator that iterates on the the list from step 1 and split it off like into smaller lists like this:
[['Name1', 'Value1'], ['Name2', 'Value2'], ['Name3', 'Value3']]

  1. Finally dict(...) on the pairs will turn them into key-value pairs in a python dictionary like this:
{'Name1': 'Value1', 'Name2': 'Value2', 'Name3': 'Value3'}

How to Split a comma separated string of dictionaries into a Pandas dataframe

Your string is invalid json, so necessary some replace first:

import ast

s = '{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}'

ss = '[' + s.replace('{', '{"').replace(':"','":"').replace('",', '","') + ']'
print (ss)

[{"apple":"34253453","oranges":"Sweet","x":"COOL"},
{"apple":"34222453","oranges":"Dry","x":"WARM"},
{"apple":"31113453","oranges":"Bitter","x":"HOT"},
{"apple":"38883453","oranges":"Sweet","x":"COOL"}]

df = pd.DataFrame(ast.literal_eval(ss))
print (df)
apple oranges x
0 34253453 Sweet COOL
1 34222453 Dry WARM
2 31113453 Bitter HOT
3 38883453 Sweet COOL

df = pd.DataFrame(pd.io.json.loads(ss))
print (df)
apple oranges x
0 34253453 Sweet COOL
1 34222453 Dry WARM
2 31113453 Bitter HOT
3 38883453 Sweet COOL

Python String to dict while separator is '='

Use split() method of string to get Key and value for dictionary item.

Use for loop to iterate on given list input.

Demo:

>>> atr = ['ID=cbs7435_mt', 'Name=cbs7435_mt', 'Dbxref=taxon:981350']>>> result_dict = {}
>>> for item in atr:
... key, value = item.split("=")
... result_dict[key] = value
...
>>> result_dict
{'Dbxref': 'taxon:981350', 'ID': 'cbs7435_mt', 'Name': 'cbs7435_mt'}
>>>


Related Topics



Leave a reply



Submit