Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting dict.items() for wxPython

I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like

[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]

I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.

I've tried iterating through the list and tuples. If I use a print statement, the output is fine. But when I replace the print statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.

I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.

Any suggestions?


Edit: Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:

BC 45
CHM 25
CMP 30

Nothing special, just simply pulling each value from each tuple and making a visual list.

I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.

like image 922
crystalattice Avatar asked Oct 28 '25 17:10

crystalattice


1 Answers

There is no built-in dictionary method that would return your desired result.

You can, however, achieve your goal by creating a helper function that will format the dictionary, e.g.:

def getNiceDictRepr(aDict):
    return '\n'.join('%s %s' % t for t in aDict.iteritems())

This will produce your exact desired output:

>>> myDict = dict([(u'BC',45), (u'CHM',25), (u'CPM',30)])
>>> print getNiceDictRepr(myDict)
BC 45
CHM 25
CPM 30

Then, in your application code, you can use it by passing it to SetValue:

self.textCtrl.SetValue(getNiceDictRepr(myDict))
like image 145
DzinX Avatar answered Oct 31 '25 07:10

DzinX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!