Again a more basic question... get a dict out of a string?

Hi! Simple example that is not working:

originalDict={ 'a':{'b':1,'c':2}, 'd':3}


copyOfOriginalDict= dict(dictString)

As said, the last line is not working because dict doesn’t retransform the dictString… - how to do it?

I need to find a way how to transfer a whole dictionary but all I have as “pipe” are variable types such as int or string… (or am I able to transfer Dictionaries using the pkg = PyDatagram() -> pkg.add[b]Dict/b ?

scratches Head

Regards, Bigfoot29


you cant convert something from string to dict in that fasion, you’d have to code something in for that. Like:

for key in myDict:

for key in myDict:
    myDict[key] = pkg.getInt()

You’re restricted to:

  • string
  • int
  • char / unsigned char
  • short / unsigned short
  • long / unsigned long
  • float / unsigned float
  • double / unsigned double

Consider using Python’s pickle module to pack things like dictionaries (and any other Python construct) into a string, and then unpack them again.


Exactly :smiley:

Thank you, David!

Here is the example code together with ‘cPickle’ (a faster, but somewhat limited (if you want to add own features to it) version of ‘pickle’!

import cPickle
originalDict={ 'a':{'b':1,'c':2}, 'd':3}


copyOfOriginalDict= cPickle.loads(dictString)

print copyOfOriginalDict
print copyOfOriginalDict['a']['c']

Attention… You migt want to use try-except for that because exceptions might occur easily :wink:

Yellow, thanks for your help as well… the problem is: I am not sure if the dict that is going to be transmitted will contain other dicts, or lists or tupels, triples, whatever :wink: - and WHERE these will be in the dict…
Pickle is doing the job here best :slight_smile: - however, your solution would be the next way I would have tried :slight_smile:

Regards, Bigfoot29

Edit: This String (dictString) can now be transmitted easily using pkg.addString()