Question

I've saved dict with QSetting, and when I load it i get QVariant

>>dict
{u'key1': u'val1', u'key2': u'val2',....}
...
>>loadedDict
<PyQt4.QtCore.QVariant object at 0x02B11848>

How to convert it back to dict so I can use it like this again:

>>dict['key2']
val2
Was it helpful?

Solution

You can convert the dict into a string and after just eval(str) it back to a dict:

pydict  = {'key1': 'val1', 'key2': 'val2'}
variant = QtCore.QVariant( pydict )
...
pydict = eval( str( variant.toString() ) )
print pydict
>>> {'key1': 'val1', 'key2': 'val2'}

Just keep in mind the eval could fail if it's not able to convert one of the keys or values from string to dict. this can happen if you have a none built_in types (str, int, list.. ) but in your case it will work no problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top