469,573 Members | 1,586 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,573 developers. It's quick & easy.

Re: Multimapping and string converting

En Fri, 19 Sep 2008 10:59:26 -0300, Ron Brennan <br*********@gmail.com>
escribió:
Hello,

I have a multimap dictionary with a 1 Key to N values. I want to convert
the N values to a string to be used elsewhere in my program.

So I have dict[(1,[1, 2 ,3 ,4])] which I have sorted

When I do a print ''.join(str(dict.value())) I get [1, 2, 3, 4] as an
output
when I really want 1 2 3 4

Here is my code:

dmapItems = dictionary.items()
dmapItems.sort()

for tcKey, tcValue in dmapItems:
file.write('Key = %s\nValue = %s" % (tcKey, tcValue)

stinger = ''.join(str(tcValue))

print stringer

The Output = [145, 2345, 567, 898]
I need it to be 145 2345 567 898
I guess you probably tried using ' '.join(value) and got an error like
this:
TypeError: sequence item 0: expected string, int found
so you inserted that str(...), but you don't still get what you want.
You want "145 2345 567 898". *If* you had a list like this: value =
["145", "2345", "567", "898"] (that is, a list of strings) *then* '
'.join(value) would do what you want. But you have this to start with
instead: value = [145, 2345, 567, 898] (a list of numbers), how to convert
it into a list of strings?
str(value) returns a single string that "looks like" a list but isn't:
"[145, 2345, 567, 898]". Instead, you need to convert each element
individually, and keep them in a list. Try this:
value = [str(elem) for elem in value]
Also, I'd use sorted() to iterate over all items. PUtting all together:

for tcKey, tcValue in sorted(dictionary.items()):
values = [str(elem) for elem in tcValue]
values = ' '.join(values)
print tcKey, values

or perhaps:

for tcKey, tcValue in sorted(find_a_good_name_for_me.iteritems()):
values_str = ' '.join(str(elem) for elem in tcValue)
print tcKey, values_str

(using lazy objects (iteritems and a generator expression) instead of
concrete lists)

--
Gabriel Genellina

Sep 19 '08 #1
0 952

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Thomas Philips | last post: by
8 posts views Thread by tim | last post: by
3 posts views Thread by Wallace | last post: by
2 posts views Thread by Deephay | last post: by
4 posts views Thread by Jonathan Wood | last post: by
10 posts views Thread by Hank Stalica | last post: by
14 posts views Thread by Mosfet | last post: by
reply views Thread by suresh191 | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.