Convert a Python Dict to a String and Back

Convert a python dict to a string and back

The json module is a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.

import json
json.dumps(dict)

Convert a String representation of a Dictionary to a dictionary

You can use the built-in ast.literal_eval:

>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}

This is safer than using eval. As its own docs say:


>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.

For example:

>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string

Converting a dictionary to string, then back to dictionary again

You should look at the json library if I understand your question, example code to load Json from a file

import json
with open('file.txt', 'r') as f:
data = json.loads(f.read())

Then to write it to a file:

import json
data = {"1": "ABC", "2": "DEF"}
with open('file.txt', 'w') as f:
f.write(json.dumps(data))

How do I serialize a Python dictionary into a string, and then back to a dictionary?

It depends on what you're wanting to use it for. If you're just trying to save it, you should use pickle (or, if you’re using CPython 2.x, cPickle, which is faster).

>>> import pickle
>>> pickle.dumps({'foo': 'bar'})
b'\x80\x03}q\x00X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02s.'
>>> pickle.loads(_)
{'foo': 'bar'}

If you want it to be readable, you could use json:

>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'
>>> json.loads(_)
{'foo': 'bar'}

json is, however, very limited in what it will support, while pickle can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__ to specify precisely how it should be pickled).

>>> pickle.dumps(object())
b'\x80\x03cbuiltins\nobject\nq\x00)\x81q\x01.'
>>> json.dumps(object())
Traceback (most recent call last):
...
TypeError: <object object at 0x7fa0348230c0> is not JSON serializable

Converting dictionary into string

Read your dictionary as key/value pairs (dict.items()) and then just format them in a string you like:

d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'}

res = ",".join("{}={}".format(*i) for i in d.items()) # a=Apple,c=cat,b=ball

The order, tho, cannot be guaranteed for a dict, use collections.OrderedDict() if order is important.

python 3 dictionary key to a string and value to another string

Use dict.items():

You can use dict.items() (dict.iteritems() for python 2), it returns pairs of keys and values, and you can simply pick its first.

>>> d = { 'a': 'b' }
>>> key, value = list(d.items())[0]
>>> key
'a'
>>> value
'b'

I converted d.items() to a list, and picked its 0 index, you can also convert it into an iterator, and pick its first using next:

>>> key, value = next(iter(d.items()))
>>> key
'a'
>>> value
'b'

Use dict.keys() and dict.values():

You can also use dict.keys() to retrieve all of the dictionary keys, and pick its first key. And use dict.values() to retrieve all of the dictionary values:

>>> key = list(d.keys())[0]
>>> key
'a'
>>> value = list(d.values())[0]
>>> value
'b'

Here, you can use next(iter(...)) too:

>>> key = next(iter(d.keys()))
>>> key
'a'
>>> value = next(iter(d.values()))
'b'

Ensure getting a str:

The above methods don't ensure retrieving a string, they'll return whatever is the actual type of the key, and value. You can explicitly convert them to str:

>>> d = {'some_key': 1}
>>> key, value = next((str(k), str(v)) for k, v in d.items())
>>> key
'some_key'
>>> value
'1'
>>> type(key)
<class 'str'>
>>> type(value)
<class 'str'>

Now, both key, and value are str. Although actual value in dict was an int.

Disclaimer: These methods will pick first key, value pair of dictionary if it has multiple key value pairs, and simply ignore others. And it will NOT work if the dictionary is empty. If you need a solution which simply fails if there are multiple values in the dictionary, @SylvainLeroux's answer is the one you should look for.

Convert dict to str

Can do this using the JSON Module:

In [409]: import json                                                                                                                                                                                       

In [410]: json.dumps(payload)
Out[410]: '{"fqdn": "domain", "duration": 1, "owner": {"city": "Paris", "given": "Alice", "family": "Doe", "zip": "75001", "country": "FR", "streetaddr": "5 rue neuve", "phone": "+33.123456789", "state": "FR-J", "type": 0, "email": "alice@example.org"}}'

After OP's comments:

In [411]: domain = 'example.com'                                                                                                                                                                            

In [412]: payload = {
...: 'fqdn': domain,
...: 'duration': 1,
...: 'owner': {
...: "city": "Paris",
...: "given": "Alice",
...: "family": "Doe",
...: "zip": "75001",
...: "country": "FR",
...: "streetaddr": "5 rue neuve",
...: "phone": "+33.123456789",
...: "state": "FR-J",
...: "type": 0,
...: "email": "alice@example.org"
...: }
...: }

In [413]: json.dumps(payload)
Out[413]: '{"fqdn": "example.com", "duration": 1, "owner": {"city": "Paris", "given": "Alice", "family": "Doe", "zip": "75001", "country": "FR", "streetaddr": "5 rue neuve", "phone": "+33.123456789", "state": "FR-J", "type": 0, "email": "alice@example.org"}}'

How to cast Python string representation of a dict back to a dict

Try:

df_loaded["dict_column"] = df_loaded["dict_column"].apply(eval)
df_loaded.iloc[0, 0]['key'] # Now returns 'val'

Best way to convert dictionary in string and remove quotes ( or ') around values

str_ = "{" + ", ".join([f"{k}: {v}" for k, v in Test.items()]) + "}"



Related Topics



Leave a reply



Submit