a = [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']
d = dict(s.split('=') for s in a)
print d


Output:
{'kkakaka': 'oeoeoeo', 'abc': 'lalalla', 'appa': 'kdkdkdkd'}

http://codepad.org/bZ8lGuHE

Answer from Demian Brecht on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-convert-key-value-pair-comma-separated-string-into-dictionary
Convert key-value pair comma separated string into dictionary โ€“ Python | GeeksforGeeks
January 22, 2025 - The key-value pair is added to the dictionary after converting the value to an integer. This method uses the re module to extract key-value pairs from the string.
Discussions

arrays - How to convert string to key value in python - Stack Overflow
I have a Django Application and want to convert a value from a string field which is comma separated to a key vaule pair and add it to a json data block. class MyClass1(models.Model): keywords = mo... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Parsing a string of key-value pairs as a dictionary - Code Review Stack Exchange
I always use nested list and dictionary comprehension for unstructured data and this is a common way I use it. In [14]: data = """ 41:n 43:n 44:n 46:n 47:n 49:n 50:n 51:n 52:n 53:n 54:n 55:cm 56:n... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
March 1, 2019
python - Convert strings of key-multiple values into key-value pairs - Stack Overflow
I have a space-separated text file. Each line has a one item followed by zero or more additional items. All values are strings. I wish to output the data as key-value pairs. How can this be done in More on stackoverflow.com
๐ŸŒ stackoverflow.com
Convert string into key-value pair array
Error is correct, String doesn't have .map() method. You need to handle else section of if block. Better See: How to create a Minimal, Complete, and Verifiable example. ... I tried converting this sting value into key value pair but not working. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Quora
quora.com โ€บ What-is-the-most-efficient-way-to-convert-a-string-of-key-value-pairs-eg-string-a-1-b-2-c-3-into-dictionary-in-Python
What is the most efficient way to convert a string of key=value pairs (eg. string = 'a=1;b=2;c=3;') into dictionary in Python? - Quora
Answer (1 of 2): I would do something like this : [code]the_dict = {} the_string = 'a=1;b=2;c=3;' for pair in the_string.split(';'): if pair: key, value in pair.split('=') the_dict[key.strip()] = value.strip() [/code]you could write this as a comprehension : [code]the_string = '...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-convert-string-list-to-key-value-list-dictionary
Python - Convert String List to Key-Value List dictionary - GeeksforGeeks
April 12, 2023 - In this, we iterate for each string, and then perform split of string using split(), assign 1st element as key and pack other elements into list, using * operator and create key-value list pair.
Top answer
1 of 4
9

Your string looks very similar to the YAML syntax. Indeed it is almost valid syntax for an associative list, there are only spaces missing after the :. So, why not use a YAML parser?

import yaml

data = """
41:n
43:n
44:n
46:n
47:n
49:n
50:n
51:n
52:n
53:n
54:n
55:cm
56:n
57:n
58:n"""

print(yaml.load(data.replace(":", ": ")))
# {41: 'n',
#  43: 'n',
#  44: 'n',
#  46: 'n',
#  47: 'n',
#  49: 'n',
#  50: 'n',
#  51: 'n',
#  52: 'n',
#  53: 'n',
#  54: 'n',
#  55: 'cm',
#  56: 'n',
#  57: 'n',
#  58: 'n'}

You might have to install it first, which you can do via pip install yaml.

2 of 4
10

You have too much logic in the dict comprehension:

{int(line.split(":")[0]):line.split(":")[1] for line in data.split("\n") if len(line.split(":"))==2}

First of all, let's expand it to a normal for-loop:

>>> result = {}
>>> for line in data.split("\n"):
...     if len(line.split(":"))==2:
...         result[int(line.split(":")[0])] = line.split(":")[1]
>>> result

I can see that you use the following check if len(line.split(":"))==2: to eliminate the first blank space from the data.split("\n"):

>>> data.split("\n")
['',
 '41:n',
 '43:n',
 ...
 '58:n']

But the docs for str.split advice to use str.split() without specifying a sep parameter if you wanna discard the empty string at the beginning:

>>> data.split()
['41:n',
 '43:n',
 ...
 '58:n']

So, now we can remove unnecessary check from your code:

>>> result = {}
>>> for line in data.split():
...     result[int(line.split(":")[0])] = line.split(":")[1]
>>> result

Here you calculate line.split(":") twice. Take it out:

>>> result = {}
>>> for line in data.split():
...    key, value = line.split(":")
...    result[int(key)] = value
>>> result

This is the most basic version. Don't put it back to a dict comprehension as it will still look quite complex. But you could make a function out of it. For example, something like this:

>>> def to_key_value(line, sep=':'):
...     key, value = line.split(sep)
...     return int(key), value

>>> dict(map(to_key_value, data.split()))
{41: 'n',
 43: 'n',
 ...
 58: 'n'}

Another option that I came up with:

>>> from functools import partial
>>> lines = data.split()
>>> split_by_colon = partial(str.split, sep=':')
>>> key_value_pairs = map(split_by_colon, lines)
>>> {int(key): value for key, value in key_value_pairs}
{41: 'n',
 43: 'n',
 ...
 58: 'n'}

Also, if you don't want to keep in memory a list of results from data.split, you might find this helpful: Is there a generator version of string.split() in Python?

Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to convert strings to dict key:value
r/learnpython on Reddit: How to convert strings to dict key:value
December 2, 2023 -

I'm trying to put together a small script that pulls and processes DNS information. I'm using dnspython to make the calls and that part is working find. Below is an example of the string I get back from it:

"v=DMARC1; p=reject; sp=reject; pct=100; fo=1; adkim=r; aspf=r; rua=mailto:me@example.net,mailto:you@example.net; ruf=mailto:dmarc@example.net"

How can I take that string and turn it into an array (I think it would be a dict in python) like this:

dns_data = {
 'v' : 'DMARC1',
 'p' : 'reject',
 'sp' : 'reject',
 'pct' : '100',
 'fo' : '1',
 'adkim' : 'r',
 'aspf' : 'r',
 'rua' : 'mailto:me@example.net,mailto:you@example.net',
 'ruf' : 'mailto:dmarc@example.net' 
}

Using strip and split I managed to get the string to a list like this:

['v=DMARC1', 'p=reject', 'sp=reject', 'pct=100', 'fo=1', 'adkim=r', 'aspf=r', 'rua=mailto:me@example.net,mailto:you@example.net', 'ruf=mailto:dmarc@example.net']

but I can't seem to figure out how to go from there to the dict and now I'm wondering if I'm just going about this the hard way and missing something simple.

๐ŸŒ
Compciv
compciv.org โ€บ guides โ€บ python โ€บ fundamentals โ€บ dictionaries-overview
Using dictionaries to store data as key-value pairs | Computational Methods in the Civic Sphere at Stanford University
However, for the most part, we'll find ourselves using strings as keys when manually creating dictionary objects and converting real-world data into dictionary objects. Just like the list object can contain a sequence of any kind of Python object, the values stored in a dictionary โ€“ and with which we use keys to access โ€“ can be any kind of Python object, such as lists or other dictionaries:
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ converting-list-string-to-dictionary-in-python
Converting list string to dictionary in Python
import ast string_data = '[name:John, age:25, city:NYC]' # Using ast.literal_eval with replace try: result = ast.literal_eval(string_data.replace("[", "{").replace("]", "}").replace(":", ": '").replace(", ", "', ") + "'") print("Converted dictionary:", result) except (ValueError, SyntaxError) as e: print("Error in conversion:", e) # Fallback to split method result = {sub.split(":")[0]: sub.split(":")[1] for sub in string_data[1:-1].split(", ")} print("Using split method:", result)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-convert-key-value-string-to-dictionary
Python - Convert key-value String to dictionary - GeeksforGeeks
April 28, 2023 - In this, we perform the conversion of key-value pairs to the dictionary using a map, and splitting key-value pairs is done using split(). ... # Python3 code to demonstrate working of # Convert key-value String to dictionary # Using map() + split() + loop # initializing string test_str = 'gfg:1, is:2, best:3' # printing original string print("The original string is : " + str(test_str)) # Convert key-value String to dictionary # Using map() + split() + loop res = [] for sub in test_str.split(', '): if ':' in sub: res.append(map(str.strip, sub.split(':', 1))) res = dict(res) # printing result print("The converted dictionary is : " + str(res))
Top answer
1 of 7
5

Use re.findall():

dict(re.findall(r'(\w+)="([^"]+)"', twikiattribs))

re.findall(), when presented with a pattern with multiple capturing groups, returns a list of tuples, each nested tuple containing the captured groups. dict() happily takes that output and interprets each nested tuple as a key-value pair.

Demo:

>>> import re
>>> twikiattribs = 'author="PersonsName" date="1183050420" format="1.1" version="1.2"'
>>> re.findall(r'(\w+)="([^"]+)"', twikiattribs)
[('author', 'PersonsName'), ('date', '1183050420'), ('format', '1.1'), ('version', '1.2')]
>>> dict(re.findall(r'(\w+)="([^"]+)"', twikiattribs))
{'date': '1183050420', 'format': '1.1', 'version': '1.2', 'author': 'PersonsName'}

re.split() also behaves differently based on capturing groups; the text on which you split is included in the output if grouped. Compare the output with and without the capturing group:

>>> re.split('(=?" ?)', twikiattribs)
['author', '="', 'PersonsName', '" ', 'date', '="', '1183050420', '" ', 'format', '="', '1.1', '" ', 'version', '="', '1.2', '"', '']
>>> re.split('=?" ?', twikiattribs)
['author', 'PersonsName', 'date', '1183050420', 'format', '1.1', 'version', '1.2', '']

The re.findall() output is far easier to convert to a dictionary however.

2 of 7
4

you can also do it without re in one line:

>>> data = '''author="PersonsName" date="1183050420" format="1.1" version="1.2"'''
>>> {k:v.strip('"') for k,v in [i.split("=",1) for i in data.split(" ")]}
{'date': '1183050420', 'format': '1.1', 'version': '1.2', 'author': 'PersonsName'}

if whitespaces are allowed inside the values you can use this line:

>>> {k:v.strip('"') for k,v in [i.split("=",1) for i in data.split('" ')]}
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python | split string key value
Python | Split String Key Value - Be on the Right Side of Change
December 6, 2022 - How will you split the string to get the key-value pairs? You have to split the string given in the problem below using the delimiter โ€œ:โ€ in such a way that everything on the left side will become keys, and everything on the right side of the delimiter becomes the values of a dictionary.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-convert-key-value-pair-comma-separated-string-into-dictionary
Convert key-value pair comma separated string into dictionary - Python - GeeksforGeeks
July 11, 2025 - The key-value pair is added to the dictionary after converting the value to an integer. This method uses the re module to extract key-value pairs from the string.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to convert a string to a dictionary in python?
How to Convert a String to a Dictionary in Python? - Be on the Right Side of Change
September 22, 2021 - You can also convert a string to a dictionary by splitting the string representation into a sequence of (key, value) pairs. Then, you can add each (key, value) pair to an initially empty dictionary after some housekeeping. ... s = '{"1": "hi", "2": "alice", "3": "python"}' def string_to_dict(s): ...